← Zurück zum Kurs: C programming from scratch

Pass by reference and week 5 review

Video folgt in Kürze

In week 3 you learned that C passes arguments by value, so a function cannot change the caller's variables. Now that you know pointers, you have the solution: pass the address of the variable. This is usually called pass by reference, although strictly C still passes a value: the address. The function receives a copy of the address, but that copy points to the same place as the original, so writing through it changes the caller's variable.

c
#include <stdio.h>

static void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

static void increment(int *counter) {
    (*counter)++;           /* parentheses: ++ would bind to the pointer otherwise */
}

int main(void) {
    int x = 3, y = 8;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);   /* x = 8, y = 3 */

    int n = 0;
    increment(&n);
    increment(&n);
    printf("n = %d\n", n);             /* 2 */
    return 0;
}

Returning several results

A function can only return one value with return. When you need more, or want to separate the result from the success status, use output parameters: pointers through which the function writes. A very common pattern is to return a status code (1 if all went well, 0 if not) and deliver the result through a pointer. The standard library does this constantly, like scanf, which receives the addresses where to store what it read.

c
#include <stdio.h>

/* Returns 1 on success and writes quotient and remainder. */
static int divide(int a, int b, int *quotient, int *remainder) {
    if (b == 0 || quotient == NULL || remainder == NULL) {
        return 0;
    }
    *quotient = a / b;
    *remainder = a % b;
    return 1;
}

static void min_max(const int *data, size_t len, int *min, int *max) {
    *min = data[0];
    *max = data[0];
    for (size_t i = 1; i < len; i++) {
        if (data[i] < *min) *min = data[i];
        if (data[i] > *max) *max = data[i];
    }
}

int main(void) {
    int q, r;
    if (divide(17, 5, &q, &r)) {
        printf("17 / 5 = %d remainder %d\n", q, r);
    }
    if (!divide(1, 0, &q, &r)) {
        printf("cannot divide by zero\n");
    }

    int values[] = {4, -2, 9, 0, 7};
    int lo, hi;
    min_max(values, 5, &lo, &hi);
    printf("min = %d, max = %d\n", lo, hi);
    return 0;
}

Beware of local addresses

A classic trap: returning the address of a local variable. When the function ends, its local variables disappear and that address is left pointing to memory that is no longer valid (a dangling pointer). Using it is undefined behavior, and the compiler usually warns with -Wall. The solutions are to receive an already reserved buffer from outside, use a static variable (with its limitations) or reserve dynamic memory, which you will see next week.

c
#include <stdio.h>

/* BAD: returns the address of a local array. */
/* static char *bad_name(void) { char buf[8] = "temp"; return buf; } */

/* GOOD: the caller provides the buffer. */
static int make_label(char *out, size_t out_size, int number) {
    int written = snprintf(out, out_size, "item-%03d", number);
    return written >= 0 && (size_t)written < out_size;
}

int main(void) {
    char label[16];
    if (make_label(label, sizeof(label), 7)) {
        printf("%s\n", label);     /* item-007 */
    }
    return 0;
}

Week 5 review: a pointer stores an address; & gets addresses and * accesses the content; NULL marks the absence of a target; adding n to a pointer advances n elements; a[i] is *(a + i); an array passed to a function becomes a pointer and loses its size; and output parameters let you modify other variables. Do the exercise and then the quiz.

Common mistakes with pointer parameters

When passing by reference there are three typical stumbles. The first is forgetting the & in the call: swap(a, b) instead of swap(&a, &b) passes the values as if they were addresses, and the program breaks when running; enable warnings, which detect it. The second is using an uninitialised pointer: declaring int *p; and writing *p = 5; writes to a random address. Initialise it to NULL or make it point to a real variable. The third is not checking NULL in the function: if you receive a pointer that may be empty, validate if (p == NULL) before dereferencing it and return an error code.

c
#include <stdio.h>

/* Returns 0 on success, -1 if a pointer is NULL. */
int swap_ints(int *a, int *b) {
    if (a == NULL || b == NULL) {
        return -1;
    }
    int tmp = *a;
    *a = *b;
    *b = tmp;
    return 0;
}

int main(void) {
    int x = 1;
    int y = 2;
    swap_ints(&x, &y);        /* note the & in the call */
    printf("%d %d\n", x, y);  /* 2 1 */
    return 0;
}

Teste dein Wissen

Frage 1 von 6

If p is an int *, what does *p = 5; do?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →