Structs and typedef: . vs ->
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Grouping related data
- A struct groups several values into one thing. A point has an
xand ay; a rectangle has awidthand aheight. - Each value inside is called a member (or field). They can have different types.
- Structs let you pass one tidy thing around instead of many loose variables.
struct and typedef
- You define the shape once:
struct { int x; int y; }has twointmembers. typedefgives that shape a short name. Aftertypedef struct { int x; int y; } Point;, you can writePoint p;.- In these tasks, the
typedefis already written for you in the starter.
Member access with .
- For a struct value, use a dot:
p.xis thexmember ofp. - You read it (
int a = p.x;) and write it (p.y = 5;) just like a normal variable. - A function can build a struct, fill its members, and
returnthe whole thing.
Through a pointer with ->
- When you have a pointer to a struct, use an arrow:
p->xmeans "thexof whatppoints to". p->xis just shorthand for(*p).x. The arrow is easier to read.- Passing a
Point *lets a function change the caller's struct (like pass-by-pointer for one value).
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main(void) {
Point p = {3, 4};
Point *ptr = &p;
ptr->x = 10; // changes p.x through the pointer
printf("%d %d\n", p.x, p.y); // 10 4
return 0;
}
Now you try
- Use
.on a struct value, and->when you have a pointer to a struct. - The
typedefis given in each starter. Do not write amain— the checker provides one.
Complete Point make_point(int x, int y) so it builds a Point with those values and returns it (use . on the members). The typedef is given. Do not write a main.
Click Run to see the output here.
Complete void move_point(Point *p, int dx, int dy) so it adds dx to the point's x and dy to its y, using ->. The typedef is given. Do not write a main.
Click Run to see the output here.
Complete int rect_area(const Rect *r) so it returns width * height, reading the members with ->. The typedef is given. Do not write a main.
Click Run to see the output here.