[SOLVED] Why is arr and &arr the same?

Issue

I have been programming c/c++ for many years, but todays accidental discovery made me somewhat curious… Why does both outputs produce the same result in the code below? (arr is of course the address of arr[0], i.e. a pointer to arr[0]. I would have expected &arr to be the adress of that pointer, but it has the same value as arr)

  int arr[3];
  cout << arr << endl;
  cout << &arr << endl;

Remark: This question was closed, but now it is opened again. (Thanks ?)

I know that &arr[0] and arr evaluates to the same number, but that is not my question! The question is why &arr and arr evaluates to the same number. If arr is a literal (not stored anyware), then the compiler should complain and say that arr is not an lvalue. If the address of the arr is stored somewhere then &arr should give me the address of that location. (but this is not the case)

if I write

const int* arr2 = arr;

then arr2[i]==arr[i] for any integer i, but &arr2 != arr.

Solution

They’re not the same. They just are at the same memory location. For example, you can write arr+2 to get the address of arr[2], but not (&arr)+2 to do the same.

Also, sizeof arr and sizeof &arr are different.

Answered By – Mr Lister

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.