简体   繁体   中英

Stack and heap memory in c++

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

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.

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).

它与对象在同一位置,因为当对象在堆上并且内部数组在堆栈上时,数组将被删除,最终得到一个空对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM