0
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};

2 Answers 2

2

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];
Sign up to request clarification or add additional context in comments.

3 Comments

So sorry for that, I misunderstood the usage of declaring a pointer array. The last line is what I really need. :-)
@KevinDong Well , no problem .It happens :)
Considering that he's assigning to {NULL, NULL}, I think it's pretty clear that he wants an array of pointers to ints.
0

Suppose you have an array of int of length 5 e.g.

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 } };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.