简体   繁体   中英

Failed to initialize a pointer array in C

int array[2] = {1, 1};
int (*pointer_array)[2] = {NULL, NULL};

The first line can be correctly compiled but not the second one? Why?

GCC compiler will pop up a warning, excess elements in scalar initializer .

How to initialize a pointer array in C?

EDITED

I declared a pointer array in a wrong way.

It should be like this:

int *pointer_array[2] = {NULL, NULL};

It should be

int (*pointer_array)[2]=(int[]){1,2};

This is pointer to array of int .I don't know you want pointer to array of int or array of pointers.

To declare as array of pointer you need to do this -

int *pointer_array[2];

Suppose you have an array of int of length 5 eg

int x[5];

Then you can do a = &x;

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

To access elements of array you: (*a)[i] ( == (*(&x))[i]== (*&x)[i] == x[i] ) parenthesis needed because precedence of [] operator is higher then * . (one common mistake can be doing *a[i] to access elements of array).

Understand what you asked in question is a compilation time error:

int (*a)[3] = {11, 2, 3, 5, 6}; 

It is not correct and a type mismatch too, because {11,2,3,5,6} can be assigned to int a[5]; and you are assigning to int (*a)[3] .

Additionally,

You can do something like for one dimensional:

int *why = (int[2]) {1,2};

Similarly, for two dimensional try this(thanks @caf):

int (*a)[5] = (int [][5]){ { 1, 2, 3, 4, 5 } , { 6, 7, 8, 9, 10 } };

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