Arrays of Structures and Pointers to Structures
Many records, and the -> operator.
5 minute read
Big idea
An array of structs holds many records. A pointer to a struct reaches members with the arrow operator ->.
Arrays of structs
One struct is one record; an array of them is a table:
#include <stdio.h>
struct Student {
char name[20];
int mark;
};
int main(void) {
struct Student cls[4] = {
{"Asha", 88},
{"Ben", 72},
{"Chen", 95},
{"Dev", 81},
};
int top = 0;
for (int i = 1; i < 4; i++) {
if (cls[i].mark > cls[top].mark) {
top = i;
}
}
printf("Top: %s with %d\n", cls[top].name, cls[top].mark);
return 0;
}output
Top: Chen with 95Run and edit it in the app.
cls[i].mark reads left to right: element i of the array, then its mark member.
Watch it
Pointers to structs and ->
With a pointer p to a struct, you could write (*p).mark — follow the pointer, then take the member. The brackets are needed because . binds tighter than *. C gives you a shortcut:
p->mark // exactly the same as (*p).mark
Changing a struct in a function
Passing a struct copies it, so a function that should change a record takes a pointer:
#include <stdio.h>
struct Person {
char name[20];
int age;
};
void birthday(struct Person p) {
p.age++;
}
int main(void) {
struct Person me = {"Riya", 19};
birthday(me);
printf("%s is %d\n", me.name, me.age);
return 0;
}output
Riya is 20Run and edit it in the app.
Change the parameter to struct Person *p, use p->age++, and call birthday(&me).
p is a pointer to a struct with a member called score. Write the expression that reads score through p, using the arrow operator.
Think of it like
A filing cabinet of identical forms (the array). Handing a colleague the drawer number (a pointer) lets them update the real form, instead of a photocopy.
🕷️ Spidey-sense: My rogues' gallery is an array of
struct Villains. When Doc Ock upgrades his arms, I updatevillains[3].threat_level— orock->threat_levelwhen I've got a pointer to his file.
Key terms
- Array of structs — Many records of the same shape.
->(arrow operator) — Member access through a pointer:p->xmeans(*p).x.
Check yourself
p is a pointer to a struct. p->age means…
Why pass a struct pointer to a function that updates it?
cls[2].name is…