Reputation: 857
If I declare a variable as
int a[100]
it is said that an array with 100 elements created on stack, and can be a bad idea depending on size etc.
Consider I define a structure
struct abc
{
int a[100];
};
and somewhere in code I utilize this structure as
abc P; //line 1
abc *p = new abc(); //line 2
Now the array is inside these two objects( one on stack(line 1) and one on heap (line 2) ). Where does the internal array reside?
Thanks
Upvotes: 1
Views: 138
Reputation: 33
It's in the same place as the object, cause when the object is on the heap and the inside array would be on the stack the array would be deleted and you end up with an empty object.
Upvotes: 0
Reputation: 13510
In line 1 the array is on the stack.
In line 2 the array is on the heap.
The struct is seen as one big variable containing all the internal arrays (and perhaps some more memory for padding and aligning) and the entire thing resides where you out it - stack or heap.
This is why you can assign struct to struct, like
s1 = s2;
and all the arrays get copied - it is handled as one big chunk of data (although it's a shallow copy, the arrays occupy real memory).
Upvotes: 0
Reputation: 1150
The location for a data member depends on the location of the object contains it. When the struct is on the stack, all its members are on the stack. When the struct is on the heap, so are the members.
Upvotes: 4