0

we have

int a[2] = { 0, 1 } ; 
std::cout << &a ;
std::cout << a ; 

Now when I run it, the output is the same for both!

Of what I have understood is that a decays to a pointer and gives me the address of the first element of the array i.e address of a[0].

Which is similar to printing std::cout << &a[0].

Now shouldn't std::cout << &a give me an error as a itself returns a pointer ?

3
  • 1
    No--the name of an array usually decays to a pointer--but not when used as the operand of the sizeof operator or the address-of operator (unary &). Commented Feb 16, 2015 at 5:47
  • It's worth pointing out that a and &a have different types, but both are convertible to void*. Commented Feb 16, 2015 at 5:48
  • 1
    There is overloaded operator<< that takes cout and a void *. All object pointers can be converted to void *, so there is no error. Commented Feb 16, 2015 at 5:52

1 Answer 1

3

First, regarding

a itself returns a pointer

No, the decay of array to pointer only happens in contexts where a pointer is expected. For example, it doesn't happen in a sizeof or decltype or typeid expression, or when the array is passed by reference to a function, or as here, when the address operator & is applied.


&a and &a[0] (or just a when decayed to pointer) refer to the same memory address, namely the first item of a, but have different types.

&a is a pointer to the whole array, and &a + 1 therefore points to a second such array following the first.

&a[0] (or just decayed a) is a pointer to the first item, and &a[0] + 1 therefore points to the second item.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.