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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With