简体   繁体   中英

Initializing pointer to array without & operator?

In the following pointer to array,

int x[5] = {1};
int (*a)[5] = &x;

what implications and consequences can i have if i don't use & operator and do like this..

int x[5] = {1};
int (*a)[5] = x; //No & operator

Can anyone explain with some good example..

Well, the type would be wrong.

in your example, x would evaluate to an int * , a pointer to the first element of x . &x , on the other hand, evaluates to int (*)[5] , a pointer to the whole array.

It's hard to come up with an example of this going wrong in practice, as an array starts with its first element by definition . But it's still wrong on a language level. Pointers can't be converted implicitly, with the one exception of void * . So, with your second example, the compiler should actually warn you (if it doesn't, add some flags, like for gcc use -std=c11 -Wall -Wextra -- or get a better compiler).

If you write the following instead:

int x[5] = {1};
int (*a)[5] = (int (*)[5])x;

it will work and should compile without warnings. Still, it's not the correct way to do it. Although in this specific case, the cast should always work as expected, you should in general avoid casting pointers in C. A pointer cast is a potential bug, so only do it when it's absolutely necessary and then double check the resulting code doesn't violate strict aliasing (look it up...).

Here, there's just no need for a cast -- write &x and you're fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM