Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Memory.

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 git diff: every line is new (+57).
--- /dev/null
+++ b/practice/08/pointers.c
@@ -0,0 +1,57 @@
+ #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) {
+ assert(a != NULL && b != NULL);
+ int tmp = *a;
+ *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) {
+ 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++) {
+ 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);
+ 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;
+ }