Drills
Drills: check yourself
Answer on your own first, and only then open the answer. Throughout:
typedef struct {
int x;
int y;
} Point;
1. What does it print?
Point a = {1, 2};
Point b = a;
b.x = 5;
printf("%d %d\n", a.x, b.x);
Answer
1 5
b = a is a separate copy.
2. What does it print?
void move(Point t) {
t.x += 100;
}
Point a = {1, 2};
move(a);
printf("%d\n", a.x);
Answer
1
move got a copy. For a to change: void move(Point *t) { t->x += 100; } and move(&a).
3. Write it differently
p is a Point *. How else can you write p->y = 7;?
Answer
(*p).y = 7; – the brackets are required because . binds tighter than *.
4. How many bytes?
typedef struct {
char c;
int x;
} A;
printf("%zu\n", sizeof(A));
Answer
8
After c there's a 3-byte gap, so that x starts at an address divisible by 4.
5. Why doesn't it compile?
Point a = {1, 2};
Point b = {1, 2};
if (a == b) {
printf("equal\n");
}
Answer
== isn't defined for structures: invalid operands to binary ==. Compare the members: a.x == b.x && a.y == b.y.