Initializing “a pointer to an array of integers”

后端 未结 4 387
一整个雨季
一整个雨季 2020-12-14 03:27
 int (*a)[5];

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

Is the below expression correct ?

int          


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 03:29

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

提交回复
热议问题