C Programming: Memory, Pointers and the Stack ยท Structs and Types

Pointers to Structs and ->

Pass a struct's address so a function can change it, and use p->field as a shortcut for (*p).field.

struct_pointers.c

#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;
}

Step by step

  1. a is created on the stack with the value {x: 1, y: 2}.
  2. ptr โ†’ a.
  3. ptr->y means (*ptr).y: a.y becomes 5.
  4. C calls move_right(), with p = โ†’ a and by = 3. It gets its own variables on the stack.
  5. Inside move_right, p โ†’ main's a, so a.x changes.
  6. move_right() has finished, so its variables are gone.
  7. The value it returned, [{x: 0, y: 0}, {x: 4, y: 4}], is stored in line.
  8. A pointer to one element of an array of structs.
  9. line changes from [{x: 0, y: 0}, {x: 4, y: 4}] to [{x: 0, y: 0}, {x: 5, y: 4}].
  10. move_right() has finished, so its variables are gone.
  11. It prints 4 5 | 5 4.
  12. The method returns 0.
  13. 4 5 | 5 4.