2

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
curiousguy
  • 8,038
  • 2
  • 40
  • 58
Nizar K
  • 29
  • 3
  • 2
    The name of an array, such as `arr` evaluates to a pointer to the first element of the array. –  Jul 07 '19 at 20:41
  • 3
    There's an implicit conversion from `int[5]` ("array") to `int*` ("pointer to first element"). There's no such conversion from `int(*)[5]` ("pointer to array") to `int*` ("pointer to first element"). If you don't want to use the implicit conversion, you can write `p = &arr[0];` (well, subscripting is defined in terms of pointer arithmetic, so implicit conversion is still used in the formal definition of how `&arr[0]` works) – Ben Voigt Jul 07 '19 at 20:41
  • 3
    An ampersand is **never** used to assign a pointer. Use `=` to do that. An ampersand takes the address of its argument. – Pete Becker Jul 07 '19 at 20:48
  • I can't agree with that closure. At least pick a question from C++ that's a dupe. Hopefully that question will have accurate citations from the related language standard explaining the "what" and "why" of that which is happening, and why the OP's code for `p = &arr;` is wrong. – WhozCraig Jul 07 '19 at 21:41
  • Arrays are special in lots and lots of different ways. This is just one of them. There's no good reason for it, it could have been done differently, but historically it wasn't and now we are stuck with it. – john Jul 07 '19 at 21:58

1 Answers1

2

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];
   ...
oo_miguel
  • 2,374
  • 18
  • 30