2

In this code ar and &ar same. But isn't arjust a constant pointer to ar[0]?Then I suppose writing cout<<ar; should give ar[0]'s memory adress while writing cout<<&ar; should give it's own memory adress so they should be different. How they are same? Some say ar is not a pointer than how cout<<*ar is equal to ar[0]'s value if it is not a pointer to ar[0] ?

int ar[3] = {1,2,3};
cout<<ar<<endl;
cout<<&ar<<endl;

I mean in this code &a and &b are different which makes sense.

   int a = 5;
    int* b = &a;
    cout<<&a<<endl;
    cout<<&b<<endl;
Alex Bravo
  • 1,601
  • 2
  • 24
  • 40
Crazy_Boy53
  • 241
  • 2
  • 4
  • 10
  • 1
    No, `arr` is not a pointer, it is an `array of 3 ints`. It can be implicitly converted to `pointer to int` though. – user7860670 Nov 03 '18 at 10:10
  • yeah, @VTT is right, `arr` is an array. Although it does contain the address of the first element, it cannot be considered as a pointer. I think whenever we use it in place of pointer, it simply decays to just a pointer. – scipsycho Nov 03 '18 at 10:12
  • 1
    How *ar is equal to ar[0]'s value if it is not a pointer to ar[0] – Crazy_Boy53 Nov 03 '18 at 10:15
  • This is a very good question. Array or pointer this is not so important. Why its own address is equal to its value??? – Andrey Chernukha Nov 03 '18 at 10:17
  • `*ar` will actually be equivalent to the following: `int * tmp_p_ar_items{static_cast(ar)}; *(tmp_p_ar_items);` while `ar[0]` will actually be equivalent to the following: `int * tmp_p_ar_items{static_cast(ar)}; *(tmp_p_ar_items + 0);`. You can check that array is not a pointer by comparing `sizeof(ar)` to `sizeof(int *)` or by using `std::is_same` – user7860670 Nov 03 '18 at 10:18
  • @VTT Looks like you're answering the question. Looks like a pretty good answer, too. Go ahead - submit an answer. – Igid Nov 03 '18 at 10:23
  • @Igid Nah, this question will be definitely closed as a duplicate. – user7860670 Nov 03 '18 at 10:26

1 Answers1

1
int ar[3] = {1,2,3};

ar here is an "array designator" wich automatically casted to pointer to the first array element. ar is equivalent to &a[0]. So that ar has a type int *

&ar ia a pointer to whole array and has type int (*)[3]

The following code is valid (pointers are compatible)

int *par0 = ar;
int (*par)[3] = &ar;

Although a and &a have different types, they have the same value — addresses of the first array element and array as a whole is the same.

ReAl
  • 1,231
  • 1
  • 8
  • 19