0

For the following code

#include<iostream>
using namespace std;
int main(){
    int arr[10];
    arr[0]=28;
    cout<<arr<<endl<<&arr<<endl<<*arr<<endl;
return 0;
}

The output is:

0x22fe88
0x22fe88
28

My doubt is that why is the value of arr and &arr same? What I know is that arr is a pointer to the first element of the array i.e. arr is same as &arr[0] and since arr is a pointer, it means that it should also have its own memory address where it is stored in memory. So why &arr and arr gives the same output? arr is supposed to give the address of first element whereas &arr should give the address of arr pointer itself. Please explain in detail.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 1
    Array is not pointer! – Vagish Aug 30 '17 at 14:22
  • Ithinkyoucanimproveyourcodingstylesoyourcodeismorereadable. Other than that, I think you should read about arrays and their relation to pointers. An array name is automatically converted to a pointer to it's first element when it's possible, it is said that arrays decay to pointers. So when you print the address of the array like that, it's converted to a pointer to the first element. Also `&arr` will point to the same place (*have the same address*), however the arithmetic on `&arr` and `arr` is not going to give the same result. – Iharob Al Asimi Aug 30 '17 at 14:22
  • @Vagish But can certainly [decay](https://stackoverflow.com/questions/1461432/what-is-array-decaying) into one. – Ron Aug 30 '17 at 14:23
  • @Ron It is "said". The context in which question asked `&arr should give the address of arr pointer itself`c , when pointer is declared , memory is allocated to store that variable itself, when array declared array symbol itself represents start of memory. So they are not same in this context. – Vagish Aug 30 '17 at 14:29
  • 1
    _What I know is that arr is a pointer to the first element of the array_ - well, this is plainly wrong. For more elaborate answer read on [what is array decaying](https://stackoverflow.com/questions/1461432/what-is-array-decaying) – rfx Aug 30 '17 at 14:31
  • @Vagish Agreed. – Ron Aug 30 '17 at 14:32

0 Answers0