Passing Structs to Functions in C
Structs pass like other values: by value (full copy — simple, potentially expensive) or by pointer (no copy, callee can modify). Small structs (a Point, a Range) pass by value readably; large ones travel as const struct * for speed with safety.
Returning structs by value is legitimate and often clear (Point mid(Point a, Point b)), with modern compilers eliding copies. For out-results, prefer a pointer parameter plus a status return over returning oversized values.
Small: pass by value
double dist(struct Point a, struct Point b) — copies of two-int structs cost nothing and can't alias.
Large: const pointer
void show(const struct Big *b) — zero copy, compiler-enforced read-only, the standard big-struct signature.
Return small values directly
struct Point mid(...) { ...; return m; } — clear ownership, copies elided in practice.
Out-params for the rest
int parse(const char *s, struct Out *o) — status return plus filled struct, C's multi-result pattern.
#include <stdio.h> typedef struct { int x; int y;} Point; Point add(Point a, Point b) { Point r = {a.x + b.x, a.y + b.y}; return r;} int main(void) { Point p = add((Point){1, 2}, (Point){3, 4}); printf("%d,%d\n", p.x, p.y); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.