0
    int a[2][2] = {{1, 2}, {3, 4}};
    cout << a << endl;
    cout << *a << endl;
    cout << &a[0][0] << endl;

The output of this code is:

     0x7fff3da96f40

     0x7fff3da96f40

     0x7fff3da96f40

However, if a is 0x7fff3da96f40 then *a should be the value in the address 0x7fff3da96f40 which is 1.

But, we get the same address again.

Why is this happening?

7
  • Try *a = 0 and you see in the error message what *a is. This is not int. Commented Oct 14, 2021 at 7:14
  • a is int (&)[2][2], *a is int(&)[2], a[0][0] is an int&. The first two decay to pointer. Commented Oct 14, 2021 at 7:59
  • It happens because a isn't 0x7fff3da96f40ais not a pointer but an array. The value you see is its decay into a pointer to its first element, &a[0] (and that first element is also an array that decays into a pointer to its first element when you print it). Commented Oct 14, 2021 at 8:09
  • 1
    @Jarod42 Excuse my nitpicking, but they aren't references. Expressions can't have reference types. Commented Oct 14, 2021 at 8:11
  • Very often, when you think "if A is true, then B should happen, so why doesn't B happen?", it is because A isn't true. Commented Oct 14, 2021 at 8:16

2 Answers 2

3

*a should be the value in the address 0x7fff3da96f40

It is. The key is what type the value has, and that type is int[2].

cout can't print arrays directly, but it can print pointers, so your array was implicitly converted to a pointer to its first element, and printed as such.

Most uses of arrays do this conversion, including applying * and [] to an array.

Sign up to request clarification or add additional context in comments.

Comments

0

If you try

int a[2][2] = {{1, 2}, {3, 4}};
cout << a << endl;
cout << *a << endl;
cout << &a[0][0] << endl;
cout << typeid(a).name() << endl;
cout << typeid(*a).name() << endl;
cout << typeid(&a[0][0]).name() << endl;

the possible output is

0x7ffe4169bb50
0x7ffe4169bb50
0x7ffe4169bb50
A2_A2_i
A2_i
Pi

So now you can see what types are the variables you are using. They are somewhat different entities, starting on same memory address.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.