Test your understanding of struct initialization, assignment, the arrow operator, and arrays of structs.
struct Point { int x; int y; }; struct Point p = {3, 7}; printf("(%d, %d)\n", p.x, p.y);
struct Point a = {1, 2}; struct Point b; b = a; b.x = 10; printf("a.x=%d, b.x=%d\n", a.x, b.x);
b becomes an independent copy of a, so changing b.x doesn't affect a.x.struct Point p = {5, 8}; struct Point *ptr = &p; printf("%d\n", ptr->y);
ptr->y is shorthand for (*ptr).y. Use the arrow operator to access members through a pointer. p.y = 8.struct Student { char name[20]; int score; }; struct Student s[3] = { {"Taro", 80}, {"Hanako", 95}, {"Jiro", 70} }; int max = 0; for (int i = 0; i < 3; i++) { if (s[i].score > s[max].score) max = i; } printf("%s\n", s[max].name);
s[1].score=95 is the highest, so max=1 and s[1].name = "Hanako".typedef struct { int x; int y; } Point; Point p = {3, 4}; printf("%d\n", p.x + p.y);
typedef struct { ... } Point; gives the struct the alias Point.
Point p; without the struct keywordtypedef makes code easier to read and is common in larger projects.
struct Point { int x; int y; }; struct Line { struct Point start; struct Point end; }; struct Line l = {{0, 0}, {3, 4}}; printf("%d\n", l.end.x);
l.end is {3, 4} (a Point struct)// Typical 64-bit environment (int=4, char=1, alignment=4) struct S { char c; int i; }; printf("%lu\n", sizeof(struct S));
int typically has to sit on a 4-byte boundary, so padding is inserted after cstruct Point { int x; int y; }; void reset(struct Point p) { p.x = 0; p.y = 0; } int main(void) { struct Point pt = {5, 10}; reset(pt); printf("%d %d\n", pt.x, pt.y); return 0; }
p is a copy of ptptpt stays as 5 10void reset(struct Point *p)) and use p->x = 0;. Passing by pointer is also a good way to avoid copy costs on large structs.
struct Point { int x; int y; int z; }; struct Point p = {5}; printf("%d %d %d\n", p.x, p.y, p.z);
struct Point p = {0}; zero-initializes every member. With C99 designated initializers, you can also initialize only specific members: {.x = 5}.