Skip to the task
Layout
Back to classic view

You are looking at lesson 8. Your place is still Practice test 2, task 1: About.

CREATETask 12 of 25 · step 6: Passing by pointerFunctions with pointers
Functions with pointers in practice/08/

swap(int *a, int *b), min_max with two results through pointers and sum, walking the array with a pointer.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.

Numbered notes in the code explain the important lines.

Details & hint
  • Where the function writes, main passes an address: swap(&x, &y), min_max(t, N, &min, &max).
  • t is passed without &: an array's name already is an address.
  • p < t + n: the loop stops at the address just past the last box.
practice 08 pointers.c Code Diff +57
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <assert.h>
#include <stdio.h>
#define N 5
/* Swaps the values of two variables.
Before: a != NULL, b != NULL. */
void swap(int *a, int *b) {
Note 1: Gets addresses, so it can change the caller's variables.
assert(a != NULL && b != NULL);
int tmp = *a;
Note 2: A third variable: without it one value would be lost.
*a = *b;
*b = tmp;
}
/* Finds the smallest and the largest value and returns them through pointers.
Before: n >= 1, t, min and max not NULL.
After: *min is the smallest, *max the largest value of t. */
void min_max(const int t[], int n, int *min, int *max) {
Note 3: Two results: return gives back only one.
assert(n >= 1 && t != NULL && min != NULL && max != NULL);
*min = t[0];
*max = t[0];
for (int i = 1; i < n; i++) {
if (t[i] < *min) {
*min = t[i];
}
if (t[i] > *max) {
*max = t[i];
}
}
}
/* The sum, walking the array with a pointer.
Before: n >= 0, t != NULL. */
int sum(const int *t, int n) {
assert(n >= 0 && t != NULL);
int s = 0;
for (const int *p = t; p < t + n; p++) {
Note 4: p++ moves to the next int, not the next byte.
s += *p;
}
return s;
}
int main(void) {
int x = 3;
int y = 8;
printf("Before: x = %d, y = %d\n", x, y);
swap(&x, &y);
Note 5: Where the function writes, pass the address.
printf("After: x = %d, y = %d\n", x, y);
int t[N] = {4, -2, 9, 0, 7};
int min;
int max;
min_max(t, N, &min, &max);
printf("Smallest: %d, largest: %d\n", min, max);
printf("Sum: %d\n", sum(t, N));
return 0;
}