1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct {
    int x;
    int y;
} Point;

void set_point_to_zero_wrong(Point p) {
    p.x = 0;
    p.y = 0;
    // WRONG because it operates on the copy of the 'Point' object that was passed as an argument.
}

void set_point_to_zero_correct(Point* a_p) {
    a_p -> x = 0;
    a_p -> y = 0;
    // CORRECT because this modifies the object in the caller's stack frame.
}

int main(int argc, char* argv[]) {
    Point p = { .x = 5, .y = 6 };

    printf("BEFORE\n");
    printf("p == { .x = %d, .y = %d }\n\n", p.x, p.y);

    set_point_to_zero_wrong(p);
    printf("AFTER set_point_to_zero_wrong(p)\n");
    printf("p == { .x = %d, .y = %d }\n\n", p.x, p.y);

    set_point_to_zero_correct(&p);
    printf("AFTER set_point_to_zero_correct(&p)\n");
    printf("p == { .x = %d, .y = %d }\n\n", p.x, p.y);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2021 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.