What an array of structs is
An array of structs is an array whose elements are structs. Each element is one record, and every record has the same fields. It suits a list of students, products or points, where you want to keep the records together and reach any one of them by its position.
The examples below use this struct:
struct Student {
std::string name;
int age;
double gpa;
};
The examples assume these headers: <algorithm>, <array>, <cstddef>, <iostream>, <iterator>, <string> and <vector>. Some features need a newer standard, and the text says which.
Declaring and initializing the array
Declare the array the same way you declare any other array, with the struct as the element type:
Student roster[3] = {
{"Ana", 20, 3.7},
{"Ben", 21, 3.2},
{"Cy", 19, 3.9}
};
Each inner set of braces fills one struct, and the values follow the order in which the members were declared. The outer braces hold the whole array.
If you list fewer values than there are elements, the rest are value-initialized. Numbers become 0 and strings become empty:
Student extra[4] = {
{"Dee", 22, 3.0}
}; // extra[1] through extra[3] have an empty name, age 0 and gpa 0.0
A local array with no initializer behaves differently. Its int and double members are left with indeterminate values, and reading them is undefined behavior. Empty braces set every member to zero:
Student blank[2]; // age and gpa are indeterminate
Student zeroed[2] {}; // every member is value-initialized
In C++20 and later, you can name the members as you initialize a struct. The names must appear in the order they were declared:
Student dee {.name = "Dee", .age = 22, .gpa = 3.0};
Struct members are public by default, so any code can read or change these fields. To control that, learn about access modifiers in c.
Reading members and looping
Pick an element with its index, then use the dot operator to reach one of its members:
std::cout << roster[0].name << " is " << roster[0].age << "\n";
roster[2].gpa = 3.95;
An index loop visits every element. std::size, available in C++17 and later, returns the number of elements in an array, using <iterator>:
for (std::size_t i = 0; i < std::size(roster); ++i) {
std::cout << roster[i].name << ": " << roster[i].gpa << "\n";
}
A range-based for loop is shorter, and it is the usual choice when you do not need the index:
for (const Student& s : roster) {
std::cout << s.name << ": " << s.gpa << "\n";
}
The const Student& reads each element by reference, so no copy is made. Use Student& if the loop needs to change the elements.
Passing an array of structs to a function
Passing an array to a function does not copy the elements. The parameter becomes a pointer to the first element, so the function cannot tell how long the array is. Send the count along with it:
void printRoster(const Student* roster, std::size_t count) {
for (std::size_t i = 0; i < count; ++i) {
std::cout << roster[i].name << "\n";
}
}
printRoster(roster, std::size(roster));
Inside printRoster, sizeof roster gives the size of a pointer, not of the array. That is why the count is passed separately.
If you want the length to stay part of the type, take the array by reference and use a template:
template <std::size_t N>
void printAll(const Student (&roster)[N]) {
for (const Student& s : roster) {
std::cout << s.name << "\n";
}
}
printAll(roster);
For the general rules, see how to pass an array to a function in c. The only new part here is that each element is a whole struct.
A function cannot return a C-style array by value. If you need one back, return a std::vector or a std::array, or wrap the array in a struct. For the options, see how to return an array in c.
std::array and std::vector instead
A C-style array has a fixed size and few built-in features. std::array keeps the fixed size and also knows its own length, so it can be copied as a single value:
#include <array>
std::array<Student, 3> roster = {{
{"Ana", 20, 3.7},
{"Ben", 21, 3.2},
{"Cy", 19, 3.9}
}};
std::cout << roster.size() << "\n"; // prints 3
If the number of records changes while the program runs, use std::vector, which grows as you add elements:
#include <vector>
std::vector<Student> roster = {
{"Ana", 20, 3.7},
{"Ben", 21, 3.2}
};
roster.push_back({"Cy", 19, 3.9});
Sorting by a field
Pass the start and end of the container to std::sort, along with a lambda that says which field to compare:
#include <algorithm>
std::sort(roster.begin(), roster.end(),
[](const Student& a, const Student& b) {
return a.gpa > b.gpa; // highest GPA first
});
This call works on a std::array too. For a C-style array, use std::begin and std::end from <iterator> in place of the member functions.
Common mistakes
- Going past the end.
roster[3]is outside a three-element array. The compiler may not catch it, and the behavior is undefined. A loop that uses<=instead of<often causes this. - Trusting sizeof inside a function. Once the array is passed as a pointer,
sizeofno longer reports the element count. Pass the count, or use the reference template. - Reading uninitialized members. A local array declared with no initializer can hold garbage in its
intanddoublemembers. Use{}to zero them. - Copying large arrays by value. A
std::array, or a struct that holds an array, is copied in full when passed by value. Pass it by reference when the function only reads it. - Forgetting the semicolon. A struct definition ends with
};. A missing semicolon usually causes a compile error that is reported on a later line. - Assuming sizeof(Student) equals the sum of its members. The compiler may add padding between members, so
sizeofcan report more bytes than the members add up to.
Choosing a container
Use a C-style array for a small, fixed list in simple code. Use std::array when the size is fixed and you want the extra features. Use std::vector when the number of records can change. In most modern C++ code, std::vector is the default choice.