Home > Back-end >  Why do arrays still point to the first element when & is infront of it
Why do arrays still point to the first element when & is infront of it

Time:03-10

In the C standard it says:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So, why when you declare &array it still points to the first element if it isn't supposed to be a pointer type?

CodePudding user response:

The actual value (i.e. memory address) of an &array expression will be the same as the address of the first element of array – but the type of the expression will not be converted to "pointer-to-element-type"; rather, it will remain as "pointer-to-array".

The difference will become apparent if you start doing pointer arithmetic on the address value:

#include <stdio.h>

int main()
{
    int arr[4] = { 1, 2, 3, 4 };
    int* p = arr   1; // p will point to the second element
    int* q = (int*)(&arr   1); // q will point past the end of the array
    //               ^ This has type "pointer to int[4]"
    // Spot the difference ...
    printf("%p %p\n", (void*)(arr), (void*)(arr   1));
    printf("%p %p\n", (void*)(&arr), (void*)(&arr   1));
    return 0;
}
  • Related