struct groups named fields into one value—C's primary way to build composite data without classes. Compare with Java POJOs or Rust structs, but without methods attached by default.
Definition and access
struct Point {
int x;
int y;
};
struct Point p = { .x = 3, .y = 4 };
printf("%d\n", p.x);
C99 designated initializers (.x = 3) clarify field assignment.
Pointers to structs
p->x is shorthand for (*p).x when p is a struct Point *.
Important interview questions and answers
- Q: struct size?
A: At least sum of members but often larger due to alignment padding—usesizeof. - Q: Copying structs?
A: Assignment copies all bytes—fine for small structs; use pointers for large ones.
Self-check
- What operator accesses a field through a struct pointer?
- Why might sizeof(struct) exceed member sizes?
Interview prep
- Struct padding?
Compiler inserts padding for alignment—
sizeof(struct)may exceed sum of member sizes.- Arrow operator?
p->memberis syntactic sugar for(*p).memberwhenpis a struct pointer.