4

我在一个 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

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

谢谢

4

2 回答 2

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]  |
            +-------------+

可以看到 index 的地址n0x76543210 + n * 2.

So you will actually have one 8-byte pointer and a million 2-byte shorts which, in your case, totals 2,000,008 bytes.

This is on top of any malloc housekeeping overhead which, like the pointer itself, is minuscule compared to your actual array.

于 2010-01-02T05:11:58.190 回答
3

No, there is only a single pointer here, not a pointer per entry. Your size estimate is 1000000*2 + 8.

于 2010-01-02T05:12:51.737 回答