不,您不会为每个数组索引获得一个指针。你得到一个指向数组的指针,这是一个连续的内存块,这就是为什么任何索引的地址都可以从索引本身加上数组地址来计算。
例如,如果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 的地址n
是0x76543210 + 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.