When you printed the various expressions, it showed you that their values were the same. However, they do not have the same types.
C and C++ include type features to reduce human mistakes and to make it easier to write complicated code. Suppose you had an address in some pointer p and C/C++ allowed you to do either:
float *f = p;
or:
int *i = p;
This would be a mistake, because, generally, whatever bits are in the memory at p do not represent both a useful int and a useful float. By enforcing rules about types, the language prevents a programmer from making a mistake here; the pointer p can only be assigned to another pointer of a compatible type, unless the programmer explicitly overrides the rules with a cast.
Similarly, your ptr
is a pointer to an array of three int
. At first, it might seem like your arr1
is also an array of three int, so you should be able to assign ptr = arr1;
. This is wrong because ptr
is merely a pointer, but arr1
is an entire array object. You cannot put an entire array into a pointer; you need to put a pointer to the array into the pointer. To get a pointer to the array, you use the &
operator: ptr = &arr1;
.
Another thing that is confusing here is that C/C++ includes an automatic shortcut: It converts an array to a pointer to the first element of the array. When arr1
appears in most contexts, it is changed automatically to &arr1[0]
. There is not a huge philosophical reason for this; it is just a convenience for the ways we often use arrays. So ptr = arr1;
would be equivalent to ptr = &arr1[0];
, which is also not allowed. In this form, you can see that arr1
has become a pointer to an int, so you cannot assign it to a pointer to an array of int. Even though the pointer has the value you want, it is the wrong type.
When an array appears as the operand of &
or sizeof
or _Alignof
, this automatic conversion does not occur. So &arr1
results in the address of the array.
A string literal that is used in an initialization such as char a[] = "abc";
is treated specially and is not automatically converted as described above.