I recently had to use an array of structs for students (struct had gpa, age, name, grade level). The first thing I did was create the array like this:
struct Student
{
//struct info
}
int main()
{
Student s1, s2, s3, s4, s5;
Student sArr[5] = {s1, s2, s3, s4, s5};
}
I proceeded to use loops to fill in the information. However, when I went to print I used the specific struct name
cout << s1.age;
and got an absurd number. I then got rid of s1 through s5 and simply printed off the array like so
cout << sArr[0].age;
I assumed that the array would store specific structs, like the ones I declared. However I learned s1.age and sArr[0].age were not the same thing. Why is this? I thought the array stored the struct s1 and sArr[0] was a reference to the struct s1.
Student sArr[5];would have the same effect (well, sans undefined behavior of accessing uninitialized objects).sArr[0]was initialized with the contents ofs1. if you edit either one, it won't affect the other since their information is not stored at the same adressesStudent, we have no idea what will be insArr. At worst the content is indeterminate. If default-construction ofStudentdelivers determinate data, terrific (it may, but we don't know because you've shown us nothing about it). By the sound of your surprise of "absurd number" content, it likely does not, and your program invokes UB. You probably want to fix that, if that is the case.