No, you don't get a pointer for each and every array index. You get a single pointer pointing to the array, which is a contiguous block of memory, which is why the address of any index can be calculated from the index itself plus the array address.
For example, if the variable a
known by the memory location 0xffff0012
is set to 0x76543210
, then they could be laid out in memory as:
+-------------+ 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] |
+-------------+
and you can see that the address of index n
is 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.