carrayspointersdereferenceaddressof

Why does pointer to array (done by &array) equal the array itself?


So I almost went all hurr durr on my classmates when they wrote that

&array gives you address of the first element

But turns out they are right. This sounds like inconsistency to me. We're talking about array defined like this:

int numbers[] = {1,2,3,4};

The variable numbers is (I think) then of type int* const. I'd think that pointer to that would be int** const. But apparently this expression evaluates as true:

if(&numbers == numbers) {
    printf("Pointer to array is still the same array!\n");
}

And of course, this then also is true:

int* first_elm_ptr = &numbers;
if(*first_elm_ptr == *numbers)
    printf("%d == %d\n", *first_elm_ptr, *numbers);

So apparently you cannot get a pointer to the variable holding address of that array. Expression &numbers is essentially meaningless. Maybe it is even removed by compiler.

How's that possible? I am very confused right now! How does standard explain this behaviour? I made an ideone test code to verify this: http://ideone.com/pYffYx


Solution

  • The address of an array and the address of the first element of the array are essentially same value (same address location). They differ in type.

    Expression &numbers is essentially meaningless

    No, it is not.

    In your case,


    Note:

    Quoting C11, chapter §6.3.2.1

    Except when it is the operand of the sizeof operator, the _Alignof 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 [....]