Pointers to Structs
beginner13 min readLesson 52 of 148
The arrow operator, struct pointers in arrays, and -> chains.
Arrow vs dot
struct Point p = {1, 2};
struct Point *pp = &p;
p.x // through the variable: dot
pp->x // through the pointer: arrow
(*pp).x // same thing, written the hard way
Walking an array of structs
struct Point pts[3] = {{1, 1}, {2, 4}, {3, 9}};
struct Point *end = pts + 3;
for (struct Point *it = pts; it < end; it++) {
printf("(%d,%d)\n", it->x, it->y); // it++ moves one WHOLE struct
}
Pointer arithmetic scales by sizeof(struct Point) โ one step, one struct.
Mixed models
A common C API shape: the array is passed as a pointer, each element used through the arrow:
int total_x(struct Point *pts, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += pts[i].x; // or (pts+i)->x
return s;
}
NULL discipline applies too
A struct pointer can be NULL; any function that receives one must either trust the contract or check it, just like int pointers.