Structs
Struct Arrays
An array can store several struct values of the same type.
array of structs
`scores[index]` selects one struct value from the array.
field after index
Use `scores[index].points` to read a field from the selected element.
Struct Arrays
struct_arrays.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
struct Score {
int id;
int points;
};
int main(void) {
struct Score scores[3] = {{1, 10}, {2, 20}, {3, 30}};
int index = 1;
int result = scores[index].points;
printf("points=%d\n", result);
return 0;
}
#include <stdio.h>
struct Score {
int id;
int points;
};
int main(void) {
struct Score scores[3] = {{1, 10}, {2, 20}, {3, 30}};
int index = 0;
int result = scores[index].points;
printf("points=%d\n", result);
return 0;
}
#include <stdio.h>
struct Score {
int id;
int points;
};
int main(void) {
struct Score scores[3] = {{1, 10}, {2, 20}, {3, 30}};
int index = 2;
int result = scores[index].points;
printf("points=%d\n", result);
return 0;
}
scores ← ⟨addr A⟩, index ← 1, result ← 20
8int main(void) {9 struct Score scores→ ⟨addr A⟩[3] = {{1, 10}, {2, 20}, {3, 30}};10 int index→ 1 = 1; //@index=0, 211 int result→ 20 = scores[index].points20;1213 printf("points=%d\n", result20);14 return 0;15}outputpoints=20
scores ← ⟨addr A⟩, index ← 0, result ← 10
8int main(void) {9 struct Score scores→ ⟨addr A⟩[3] = {{1, 10}, {2, 20}, {3, 30}};10 int index→ 0 = 0;11 int result→ 10 = scores[index].points10;1213 printf("points=%d\n", result10);14 return 0;15}outputpoints=10
scores ← ⟨addr A⟩, index ← 2, result ← 30
8int main(void) {9 struct Score scores→ ⟨addr A⟩[3] = {{1, 10}, {2, 20}, {3, 30}};10 int index→ 2 = 2;11 int result→ 30 = scores[index].points30;1213 printf("points=%d\n", result30);14 return 0;15}outputpoints=30