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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

#define log_int(n) printf("%s == %d\n", #n, n)
#define log_addr(n) printf("%s == %p\n", #n, (void*)(n))
#define log_point(n) printf("%s == (%d,%d)\n", #n, (n).x, (n).y)

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

// using struct addresses to modify the data in the original struct
void multiply_point(Point* point, int multiplier) {
    point->x *= multiplier;
    point->y *= multiplier;
}

// using struct addresses to save memory
// (note that in this example, the memory usage is the same, we need a larger struct to really save memory)
void print_point(const Point* point) {
    // disallowed because its const
    //point->x = 0;
    printf("(%d, %d)\n", point->x, point->y);
}

int main(int argc, char* argv[]) {
    Point p1 = { .x = 7, .y = 843 };
    log_point(p1);

    Point* a_p1 = &p1;
    log_addr(a_p1);
    log_int(p1.x);
    // *a_p1.x === *(a_p1.x)
    log_int((*a_p1).x);
    log_int(a_p1->x);
    log_point(*a_p1);

    a_p1->x = -371;
    log_point(p1);

    Point p2 = { .x = 91, .y = 331 };
    // this line *copies* p2 into p1
    *a_p1 = p2;
    log_addr(a_p1);
    log_point(p1);
    log_point(p2);
    a_p1->y = 100;
    log_point(p1);
    log_point(p2);
    // henceforth, a_p1 is the address of p2, not p1 anymore
    a_p1 = &p2;
    log_addr(a_p1);
    a_p1->x = 0;
    log_point(p1);
    log_point(p2);

    Point p3 = { .x = 43, .y = 89 };
    log_point(p3);
    multiply_point(&p3, 10);
    log_point(p3);
    print_point(&p3);
    log_point(p3);
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2024 Alexander J. Quinn & David Burnett         This content is protected and may not be shared, uploaded, or distributed.