Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding relationship between arrays and pointers

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?

like image 843
fbi open_up Avatar asked Mar 09 '26 11:03

fbi open_up


2 Answers

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).

like image 175
songyuanyao Avatar answered Mar 11 '26 01:03

songyuanyao


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.

like image 45
Some programmer dude Avatar answered Mar 11 '26 01:03

Some programmer dude