Structs
Prerequisites: The preprocessor and macros
A struct groups related values of possibly different types under
one name — C's building block for modeling real-world things,
without any of the classes or methods of an object-oriented
language.
Syntax
struct Point {
int x;
int y;
};
Example
struct Point p = {3, 4};
printf("%d, %d\n", p.x, p.y);
p.x = 10;
printf("%d\n", p.x);
Expected output
3, 4
10
A struct is passed to a function by value by default (the whole thing is copied) — pass a pointer to it instead when the function needs to modify the original, or to avoid copying a large struct:
void movePoint(struct Point *p, int dx, int dy) {
p->x += dx; // -> is shorthand for (*p).x
p->y += dy;
}
Common mistakes
- Writing
p.xwhenpis actually a pointer to a struct (struct Point *p) — that needsp->x(or the equivalent but clunkier(*p).x).
Practice
Define a struct Rectangle with width and height, and write a
function that returns its area.
Show solution
struct Rectangle {
int width;
int height;
};
int area(struct Rectangle r) {
return r.width * r.height;
}