The short answer
A struct groups named members, and those members can have different types. An array holds a numbered sequence of elements, and all of its elements have the same type. Use a struct when the fields describe one thing. Use an array when you have many items of the same kind.
What a struct looks like
struct Student {
std::string name;
int age;
double gpa;
};
Student ana {"Ana", 20, 3.7};
std::cout << ana.name << " has a GPA of " << ana.gpa << "\n";
Each member is reached by name, with the dot operator.
What an array looks like
int scores[4] = {90, 85, 77, 100};
int second = scores[1]; // indexes start at 0
Each element is reached by its position. Every element is an int, so the array cannot mix types.
Comparing them
| Struct | Array | |
|---|---|---|
| Elements | Named members, which can have different types | Numbered elements, all of one type |
| Access | By name, with the dot operator, as in ana.gpa |
By index, starting at 0, as in scores[1] |
| Size | Set by the members it declares | Set by the count written when the array is declared |
| Assignment | b = a copies every member |
A C-style array cannot be assigned with = |
| Passing to a function | Copied as a whole, unless passed by reference | Passed as a pointer to the first element, so the length must be sent separately |
A struct can hold an array
A struct can have an array as one of its members. Using the Student struct from above:
struct Team {
std::string name;
Student members[5];
};
Assigning one Team to another copies the array too, because a struct copies all of its members. A C-style array on its own cannot be copied that way with =.
An array of structs
The two ideas combine. An array of structs holds many records, and each record has named fields:
Student roster[3] = {
{"Ana", 20, 3.7},
{"Ben", 21, 3.2},
{"Cy", 19, 3.9}
};
std::cout << roster[1].name << "\n"; // prints Ben
A list of records like this is what people mean by an array of structs in C.
Which one to use
- Use a struct when the fields describe one thing, such as a point with an x and a y value, or a student with a name, age and GPA.
- Use an array when you have many items of the same type and need to go through them by position, such as a row of exam scores.
- Use an array of structs when you have many records, and each one has several fields.
- When the number of items can change while the program runs, use
std::vectorin C++. A C-style array has a fixed size.
A note on layout
An array of structs keeps each record’s fields together. Some performance-focused code uses the opposite arrangement, a struct of arrays, where each field has its own array. That can help when a loop reads only one field, but it is harder to read and maintain. Measure before you change a layout.
Summary
A struct groups different named fields for one thing. An array holds many values of one type, reached by position. In practice you often use both together: an array of structs, where each element is one record.