C Programming: Memory, Pointers and the Stack ยท Structs and Types
Pass a struct's address so a function can change it, and use p->field as a shortcut for (*p).field.
#include <stdio.h>
struct Point {
int x;
int y;
};
void move_right(struct Point *p, int by) {
p->x += by; /* p->x means (*p).x */
}
int main(void) {
struct Point a = {1, 2};
struct Point *ptr = &a;
ptr->y = 5;
move_right(&a, 3);
struct Point line[2] = {{0, 0}, {4, 4}};
move_right(&line[1], 1);
printf("%d %d | %d %d\n", a.x, a.y, line[1].x, line[1].y);
return 0;
}a is created on the stack with the value {x: 1, y: 2}.move_right(), with p = โ a and by = 3. It gets its own variables on the stack.move_right() has finished, so its variables are gone.line.line changes from [{x: 0, y: 0}, {x: 4, y: 4}] to [{x: 0, y: 0}, {x: 5, y: 4}].move_right() has finished, so its variables are gone.4 5 | 5 4.0.