Array of structs
- C course
- Beginner
- Lesson 97/116
- 5 min
Learn to create an array of structs and iterate it.
Array of structs
You can declare an array of a struct type. This is ideal to manage multiple records under one structure.
struct Point points[3] = {
{1, 2},
{3, 4},
{5, 6}
};Here points holds three struct Point. Each element carries its own x and y. You access the first point's x with points[0].x. You can loop over all points.
Looping over a struct array
You can iterate over a struct array with a for loop. For each element, member access uses the [i].member form.
for (int i = 0; i < 3; i++) {
printf("%d %d\n",
points[i].x,
points[i].y);
}Here i goes from 0 to 3; each step prints one point's coordinates. The chain points[i].x first takes the i-th element, then reaches its x member. This pattern is standard to process data tables.
Practice Print three points
Define struct Point (int x, int y). In main create a three-point array: {{1, 2}, {3, 4}, {5, 6}}. Use a for loop to print each point with printf.
Starter code
#include <stdio.h>
struct Point { int x; int y; };
int main(void) {
/* Declare an array of three Points; loop with for; print with printf */
return 0;
}Sample solution
struct Point points[3] = {{1, 2}, {3, 4}, {5, 6}};
for (int i = 0; i < 3; i++) {
printf("%d %d\n", points[i].x, points[i].y);
}Expected output
1 2 3 4 5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does points[1].x represent?
- The x member of the 2nd element
- The x member of the first element Correct answer
- A Point pointer
- All x members of the array
Explanation: points[1] is the second element; .x is its x member.
2 Match expression to meaning
| Term | Meaning |
|---|---|
points[0] |
First element |
points[2] |
Third element |
points[i].x |
x of i-th element |
points[3] |
Out of bounds |
3 Fill in the blank: array element access
printf("%d
", points____);
printf("%d
", points[0].x);
Explanation: points[0].x gives the first element's x member.