how do arrays work internally in c/c++

arrays when even declared with the square brackets ([]) are actually in memory a sequence of n pointers each containing […] the address of a memory box Bi containing the actual value + those memory boxes

Nope.

It sounds like you’re puzzled how array[0] == *(array+0) == *array could be true both for an array declared as int array[10]; and int *array = ...;. A perfectly reasonable question; We’re told that for a pointer ptr the expression *ptr gets the value the pointer is pointing at, so when we use the same syntax with an array where are the addresses that we’re dereferencing?

Here’s the secret: The array index operator ([]) does not work on arrays in C and C++. When you apply it to an array the language implicitly converts the array into a pointer to the array’s first element. Thus adding to an array or dereferencing an array appears to behave the same as adding or dereferencing a pointer.

int array[10];

// These lines do exactly the same thing:
int *ptr1 = &array[0]; // explicitly get address of first element
int *ptr2 = array;     // implicitly get address of first element

So arrays really are a contiguous set of elements in memory where each element really is the value, not a pointer to another location containing the value. It’s just that the way arrays are defined means that they often convert to a pointer implicitly and so it seems like there are pointers when really there’s just an implicit conversion.

Leave a Comment