|wasn't this supposed to be int* ptre = foo;|
Yes. Sorry. Typo. I've corrected that in my post. Thanks.
|int (*ptr) = foo instead of &foo???|
They are mismatching types.
The key is to remember what type each variable is. For example, here we have 4 types:
int ar; // type = int4
int (*ptar); // type = int4* (a pointer to an int4)
int var; // type = int
int* ptvar; // type = int* (a pointer to an int)
Throw a & before those variables and you get a pointer to whatever type it was:
&ar; // ar was an int4, so &ar is an int4*
&ptar; // was int4*, now is int4**
&var; // was int, now is int*
&ptvar; // was int*, now is int**
You can only assign like types. Back to the original example with foo and ptr:
int (*ptr) = &foo;
foo is int4
ptr is int4*
Those are 2 different types: one is an array, the other is a pointer to an array. Therefore you cannot assign them.
ptr = &foo
&foo is int4*
ptr is int4*
They're the same type... so they can be assigned.
The only oddity here is that there is an implicit cast
that happens when you take an array name without brackets. This is what is confusing for newbies:
int* ptr = array; // strangely legal... but why?
This is strange because:
array is int4
ptr is int*
They are different types
. So why can you assign them? Why is this legal?
The weirdness here is that if you have an array name (in this case, 'array') and you do not give it braces, it is implicitly cast to a pointer to the first element in the array.
int array; // int4
int* ptr; // int*
array; // int
&array; // int*
ptr = &array; // both are int*, so assignment is OK
ptr = array; // int* = int4 -- mismatching types... but the compiler will automatically
// cast 'array' to be '&array'
// so you get a pointer to the first element. So this assignment is OK after all.