Why is an ampersand operator used only sometimes to assign a pointer in C++?

773 Views Asked by At

Can someone explain why assigning an array's memory address to a pointer isn't the same as assigning a 'normal' variable's to a pointer? (int a; int* p = &a;)

I know for a fact that the ampersand in front of the array (&arr) points to its memory address, so why doesn't it work to assign it to a pointer this way?

float* p;
float arr[5];
p = arr; // why is this correct 
p = &arr; // and this isn't
1

There are 1 best solutions below

0
oo_miguel On

Quote from Working Draft, Standard for Programming Language C++:

4.2 Array-to-pointer conversion

An lvalue or rvalue of type “array of N T ” or “array of unknown bound of T ” can be converted to a prvalue of type “pointer to T ”. The result is a pointer to the first element of the array.

So arr is the same as &arr[0] in your example, which is a pointer to the first element of the array.

Notice that you can also do this however:

float (*p)[5]; // pointer to array
float arr[5];
p=&arr;

and access your elements with:

   (*p)[0];
   (*p)[1];
   (*p)[2];
   ...