Initializing arrays of structs
What you'll learn: How to cleanly populate a list of custom data objects using nested curly braces.
Organizing the catalog
Once you know how to create a struct to represent a single object—like a book or a player—you will often need to group them. An array of structures is the perfect tool for this. However, instead of assigning values to every variable one by one (which is tedious), C allows you to initialize the entire list at once using a "nested" syntax.
Think of it like filling a pill organizer. The organizer itself is the array, and each daily slot is a struct. To fill it efficiently, you don't just throw pills in a pile; you place a specific set of medicine into each labeled compartment.
The nested brace syntax
To initialize an array of structs, you use a set of curly braces for the array, and inside those, another set of curly braces for each individual struct. Each internal set must follow the order of members defined in your struct template.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
// Initializing an array of 3 Point structs
struct Point path[3] = {
{0, 0}, // The first struct in the array
{5, 10}, // The second struct
{12, 7} // The third struct
};
// Accessing the second point's X coordinate
printf("Second point X: %d\n", path[1].x);
return 0;
}
Why this matters
In the code above, the compiler looks at the first pair {0, 0} and knows that 0 goes to x and the second 0 goes to y because that is the order defined in the struct Point.
If you have a large array, this method is significantly cleaner than writing path[0].x = 0; path[0].y = 0; over and over. Furthermore, if you leave the array size empty (e.g., struct Point path[] = ...), C will automatically count the number of initialized blocks you provided and set the array size for you. This makes your code more flexible if you decide to add more data points later.
Key takeaway
Use nested curly braces—{{...}, {...}}—to populate an array of structs in a single, readable statement.