← Structs and UnionsC PROGRAMMING 1.4.B

Structs and Pointers

Pointer-to-struct, -> vs (*p).field, passing structs by pointer.

StatusCollected
NotesChapter test: 4/5

Pointer-to-struct, the -> shorthand, and passing structs by pointer instead of by value — this is the one that actually matters for anything beyond toy examples.

struct point p = {10, 20};
struct point *pp = &p;

(*pp).x = 99;    /* works, but clunky — the parens are required (. binds tighter than *) */
pp->x = 99;      /* identical meaning, this is what actually gets written */

-> is just (*p). with less noise — dereference the pointer, then access the member, in one operator.

Passing by pointer

Passing a struct by value copies the whole thing onto the stack — fine for something the size of a point, wasteful and slow for anything bigger. Passing a pointer instead copies just the address, and is also the only way a function can actually modify the caller's struct rather than a throwaway copy of it.

Notes from readers

Comments — via GitHub