c/c ++中指针的内存开销

mon*_*ing 4 c c++ memory pointers overhead

我在64位平台上,因此所有内存adrs都是8个字节.

因此,为了估计数组的内存使用情况,我应该为数组中的每个条目的sizeof(DATATYPE)添加8个字节.

例:

short unsigned int *ary = new short unsigned int[1000000]; //length 1mio
//sizeof(short unsinged int) = 2bytes 
//sizeof(short unsinged int*) = 8 bytes
Run Code Online (Sandbox Code Playgroud)

那么每个条目占用10个字节吗?因此,我的1mio长度数组是否会使用至少10兆字节?

谢谢

pax*_*blo 33

不,你没有得到每个数组索引的指针.你得到一个指向数组的指针,这是一个连续的内存块,这就是为什么可以从索引本身加上数组地址计算任何索引的地址.

例如,如果a内存位置已知的变量0xffff0012设置为0x76543210,则它们可以在内存中布局为:

            +-------------+ This is on the stack or global.
0xffff0012  |  0x76543210 |
            +-------------+

            +-------------+ This is on the heap (and may also
0x76543210  |  a[     0]  |   have some housekeeping information).
            +-------------+
0x76543212  |  a[     1]  |
            +-------------+
0x76543214  |  a[     2]  |
            +-------------+
0x76543216  |  a[     3]  |
            +-------------+
               :       :
            +-------------+
0x7672B68E  |  a[999999]  |
            +-------------+
Run Code Online (Sandbox Code Playgroud)

你可以看到索引的地址n0x76543210 + n * 2.

所以你实际上有一个8字节指针和一百万个2字节短路,在你的情况下,总共2,000,008字节.

这是在任何malloc家务开销之上,与指针本身一样,与实际阵列相比微不足道.