I was recently reading about difference between T* and T[size], T being the type, and it make me curious so I was playing around with it.
int main()
{
int a[10];
using int10arrayPtr_t = int(*)[10];
int10arrayPtr_t acopy = a;
}
In the above code, int10array_t acopy = a; is an error with message
error C2440: 'initializing':
cannot convert from 'int [10]' to 'int10array_t'
And this compiles:
int main()
{
int a[10];
using int10arrayPtr_t = int*;
int10arrayPtr_t acopy = a;
}
Isnt the type int(*)[10] closer the the type of int a[10]; than int*? So why does it not allow the first case?
You need to take the address explicitly, e.g.
int10arrayPtr_t acopy = &a; // acopy is a pointer to array containing 10 ints
// ^
The 2nd case works because array could decay to pointer, for a, it could convert to int* implicitly, and acopy is a pointer to int (note that it's not a pointer to array).
In your first example, the symbol int10arrayPtr_t is an alias for a "pointer to an array of 10 integers". In your second example the same symbol is an alias for "pointer to a single integer". That's quite a different thing.
Also, it's true that arrays decays to pointers to their first element, but it's a pointer to a single element of the array. I.e. plain a will decay to &a[0], which have the type int*. To get a pointer to the array you need to use the pointer-to operator & for the whole array, as in &a.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With