2

Below, in my program I defined an array of integer type named myArray. After that it prints the value of both myArray and &myArray :

#include <iostream>

using namespace std;

int main()
{
    int a[2] = {2,3};
    cout<<a<<endl<<&a;
    return 0;
}

In the output this two value are equal! For example this is output in my computer:

ap1019@sharifvm:~$ ./a.out
0x799188ebe4d0
0x799188ebe4d0 

I know that the identifier of an array is a pointer to the first element of it, but why the value of this pointer is equal with its address?

Abraham
  • 5,544
  • 10
  • 40
  • 95
  • 2
    The short answer is "because that is the way the language defines it". This is why you can do `int *p = malloc(10 * sizeof *p); p[0] = 1;` - i.e. treat pointers as arrays, – kdopen Apr 24 '15 at 16:12
  • 1
    Also a duplicate of http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c – kdopen Apr 24 '15 at 16:14
  • "I know that the identifier of an array is a pointer to the first element of it" - for a programmer, the identifier might look like a pointer (properties like dereferencing and having an address as its value), but actually the identifier is not a pointer (in the implementation) and that is the reason you see the identifier address as its value (compiler ignores the `&` operator on a identifier). And as said by @kdopen, that is why you can do `int* p = malloc(some_size); p[0] = 1`. The way you access an array identifier and p remains the same (but implementation is not the same) – infinite loop Jun 07 '17 at 15:30

0 Answers0