Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c - Initializing "a pointer to an array of integers"

 int (*a)[5];

How can we Initialize a pointer to an array of 5 integers shown above.

Is the below expression correct ?

int (*a)[3]={11,2,3,5,6}; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 an 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 p[2]) {1,2};

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...