MPS
MPS

Reputation: 131

Dereferencing array address does not work?

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)?

Upvotes: 2

Views: 93

Answers (2)

Van Tr
Van Tr

Reputation: 6121

&myArray is the address of the entire array object not the first element; it's a pointer expression of type int(*)[3]

You could refer this with a very quality accepted answer

Are a, &a, *a, a[0], &a[0] and &a[0][0] identical pointers?

Upvotes: 2

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17434

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.

Upvotes: 7

Related Questions