C++11 code:
int a[3];
auto b = a; // b is of type int*
auto c = &a; // c is of type int(*)[1]
C code:
int a[3];
int *b = a;
int (*c)[3] = &a;
The values of b
and c
are the same.
What is the difference between b
and c
? Why are they not the same type?
UPDATE: I changed the array size from 1 to 3.
The identity of any object in C++ is determined by the pair of its type and its address.
There are two distinct objects with the same address in your example: The array itself, and the first element of the array. The first has type
int[1]
, the second has typeint
. Two distinct objects can have the same address if one is a subobject of the other, as is the case for array elements, class members, and class base subobjects.Your example would be clearer if you wrote:
But you have taken advantage of the fact that the id-expression
a
for the array decays to a pointer to the array's first element, soa
has the same value as&a[0]
in your context.Consider this example:
You will find that all the 5 values printed in first case are all equal. Because they point to the same initial location.
But just when you increment them by 1 you see that different pointers now jump (point) to different locations. This is because
myArray[0][0][0] + 1
will jump by 10 integer values that is 40 bytes, whilemyArray[0][0] + 1
will jump by 100 integer values i.e by 400 bytes. SimilarlymyArray[0] + 1
jumps by 1000 integer values or 4000 bytes.So the values depend on what level of pointer you are referring to.
But now, if I use pointers to refer all of them:
So you see, different levels of pointer variables do not behave the way the array variable does.
The
sizeof
operator should behave differently, for one, especially if you change the declaration ofa
to a different number of integers, such asint a[7]
:For me, this prints:
That's because the two pointers are very different types. One is a pointer to integer, and the other is a pointer to an array of 7 integers.
The second one really does have pointer-to-array type. If you dereference it, sure, it'll decay to a pointer in most cases, but it's not actually a pointer to pointer to int. The first one is pointer-to-int because the decay happened at the assignment.
Other places it would show up is if you really did have two variables of pointer-to-array type, and tried to assign one to the other:
This earns me the error message:
This example, however, works, because dereferencing
bb
allows it to decay to pointer-to-int:Note that the decay doesn't happen on the left side of an assignment. This doesn't work:
It earns you this: