Search code examples
c++arrayspointersmemory

What does a pointer to an array represent?


I found out that arrays are actually similar to pointers and the variable they are contained in gives 1 element of the array when unpacking. So does a pointer that points to that array, and my question is why if we increment the pointer by one (using an increment) we will get the next element in the array? Are all the array elements next to each other in memory?


Solution

  • Recently I found out that arrays are actually similar to pointers

    This statement is wrong. Arrays are not pointers, period. However, in certain contexts, such as variable/parameter assignment, an array can decay into a pointer to its 1st element.

    So does a pointer that points to that array

    A pointer to the array itself, and a pointer to an element of an array, are two completely different things, even if they happen to point at the same memory address (ie, when pointing at the 1st element).

    why if we increment the pointer by one (using an increment) we will get the next element in the array.

    That is just simple pointer arithmetic. When you increment a typed pointer, the memory address it holds is incremented by the byte size of the type of the pointer. So, for example:

    T arr[2];
    T* ptr_1 = arr;       // ie &arr[0]
    T* ptr_2 = ptr_1 + 1; // ie reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(ptr_1) + sizeof(*ptr_1))
    

    ptr_1 points at the 1st element in arr[0], and ptr_2 points at the 2nd element in arr[1], because ptr_1 is of type T* so the address in ptr_2 is sizeof(T) bytes higher than the address in ptr_1:

    arr
    +-------+-------+
    |   0   |   1   |
    +-------+-------+
    ^       ^
    ptr_1   ptr_2
    

    Now, take the same concept and apply it to a pointer to the array itself, rather than a pointer to an element:

    using ArrayOfT2 = T[2];
    ArrayOfT2 arr;
    ArrayOfT2 *ptr_1 = &arr;
    ArrayOfT2 *ptr_2 = ptr_1 + 1; // ie reinterpret_cast<Array2*>(reinterpret_cast<uintptr_t>(ptr_1) + sizeof(*ptr_1))
    

    ptr_1 points at arr itself, and ptr_2 points at the address after arr, because ptr_1 is of type ArrayOfT2* so the address in ptr_2 is sizeof(ArrayOfT2) bytes higher than the address in ptr_1:

    arr
    +-------+-------+
    |   0   |   1   |
    +-------+-------+
    ^               ^
    ptr_1           ptr_2
    

    Are all the array elements next to each other in memory?

    Yes. An array is always stored as a single contiguous block in memory.