简体   繁体   中英

What's the type difference between a, &a, and &a[0]?

#include <iostream>

void arrayFunctionA(int* p)
{
}

int main()
{
    int a[3] = {7, 7, 7};
    arrayFunctionA(a);
    arrayFunctionA(&a[0]);
    arrayFunctionA(&a);
    return 0;
}

This will not compile, with an error on arrayFunctionA(&a); .

So, a and &a[0] evaluates as int* , but &a does not.

What is the distinction between these 3?

a is an array of 3 int type ( int [3] ).

A fixed array decays to a pointer to its first element, so in arrayFunctionA(a) , a will decay into an int* pointer to it's first element.

&a[0] is the address of the array's first element, and is of type int * .

&a is the address of the array itself, and is of type int (*)[3] (pointer to an array of 3 int ).

So, for a function with signature

void arrayFunctionA(int* p);

Passing a or &a[0] will serve the same purpose, while passing &a will result in an incompatibility between the passed argument value and the function parameter.

The first two examples are identical.

  • In the first one, a decays to a pointer and binds to the int* taken by the function.
  • In the second one, &a[0] is identical to &*(p + 0) which yields a int* .

The third example doesn't compile because applying the address-of operator ( & ) to an array yield a pointer to an array. In your example the result is a int(*arr)[3] which cannot bind to a int* so you get the compilation error.

Оn the first call arrayFunctionA(a); the actual address of a is being passed.

Оn the second call arrayFunctionA(&a[0]); the actual address of index 0 is being passed.

The first and second calls are identical. You both get the address of index 0 (remember that an array is also a pointer).

On the third call you are getting the pointer of a which is already a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM