wasn't this supposed to be int* ptre = foo; |
Yes. Sorry. Typo. I've corrected that in my post. Thanks.
int (*ptr)[4] = foo instead of &foo??? |
No.
They are mismatching types.
The key is to remember what type each variable is. For example, here we have 4 types:
1 2 3 4
|
int ar[4]; // type = int4
int (*ptar)[4]; // 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:
1 2 3 4
|
&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:
1 2
|
int foo[4];
int (*ptr)[4] = &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.
However..
ptr = &foo
works because:
&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:
1 2
|
int array[4];
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.
IE:
1 2 3 4 5 6 7 8 9 10
|
int array[4]; // int4
int* ptr; // int*
array[0]; // int
&array[0]; // int*
ptr = &array[0]; // both are int*, so assignment is OK
ptr = array; // int* = int4 -- mismatching types... but the compiler will automatically
// cast 'array' to be '&array[0]'
// so you get a pointer to the first element. So this assignment is OK after all.
| |