Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing array address does not work?

Tags:

c++

arrays

Considering the following code:

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

std::cout << myArray << "\n"; // 0x22ff24
std::cout << &myArray << "\n"; // 0x22ff24
std::cout << *myArray << "\n"; // 1
std::cout << *(&myArray) << "\n"; // 0x22ff24

Why does the bottom statement not give 1, like the 3rd statement? If myArray is equal to &myArray, why is *myArray not equal to *(&myArray)?

like image 309
MPS Avatar asked Jun 22 '26 19:06

MPS


1 Answers

The reason for the behaviour is that the type of &myArray is a pointer to the array. Dereferencing yields a reference to the array and when outputting, the array decays to a pointer to its first element.

Your confusion probably comes from the fact that the array and its first element have the same address. However, not only the address but also the type of an expression have an influence how it is evaluated.

like image 191
Ulrich Eckhardt Avatar answered Jun 25 '26 10:06

Ulrich Eckhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!