Ben Hogan
Ben Hogan

Reputation: 33

C++ struct arrays

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.

Upvotes: 3

Views: 245

Answers (2)

Michael Veksler
Michael Veksler

Reputation: 8475

Unlike Python, C#, Java, and JavaScript, copying an object is done by value and not by reference. For simple objects that have no pointers or references this means that copying an object, such as a struct Student is performed as a deep-copy.

The C++ compiler generates a copy constructor for struct Student, which copies field by field (recursively) from s1 to sArr[0]. You can define your own copy constructor, to define how the object is to be copied. In a code like yours, the object is copied, not a reference.

If you want only to copy a reference, then in your example you have to use pointers. Python, C#, and Java references are an entity which is slightly more restricted than C++ pointers. That is why in your solution you will need to use pointers:

struct Student 
{ 
  //struct info 
};
int main()
{ 
   Student s1, s2, s3, s4, s5;
   Student *sArr[5] = {&s1, &s2, &s3, &s4, &s5}; 
}

When you have:

sArr[0]->age=10;

Then the age of s1 is updated.


Another alternative is to put the objects in the array, and use named references to access them:

struct Student 
{ 
  //struct info 
};
int main()
{ 
   Student sArr[5];
   Student &s1 = sArr[0];
   Student &s2 = sArr[1];
   Etc...
}

The difference between Python references and C++ references, is that C++ references can't be reassigned and can't be null.

Upvotes: 2

Shivanshu
Shivanshu

Reputation: 894

You are getting absurd answer because you are assigning a variable into array element that is in fact another variable, so this is like copying one variable attributes into other.It doesn't mean at all that referencing one variable will lead us to modify into another variable.

int a=10,c=12;
int b[2]={a,b};

In this case it doesn't mean that changing in variable a will lead us to changing in b[0] and vice versa. So the way to do it is creating array of pointer ,whose each element is made to accept the address of struct variable so that changing in variable or array element would reflect the changed value into another.

Upvotes: 1

Related Questions