Initializing “a pointer to an array of integers”

后端 未结 4 374
一整个雨季
一整个雨季 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:27
    int vals[] = {1, 2};
    int (*arr)[sizeof(vals)/sizeof(vals[0])] = &vals;
    

    and then you access the content of the array as in:

    (*arr)[0] = ...
    
    0 讨论(0)
  • 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 } };
    
    0 讨论(0)
  • 2020-12-14 03:33
    int a1[5] = {1, 2, 3, 4, 5};
    int (*a)[5] = &a1;
    
    0 讨论(0)
  • 2020-12-14 03:41

    {11,2,3,5,6} is an initializer list, it is not an array, so you can't point at it. An array pointer needs to point at an array, that has a valid memory location. If the array is a named variable or just a chunk of allocated memory doesn't matter.

    It all boils down to the type of array you need. There are various ways to declare arrays in C, depending on purpose:

    // plain array, fixed size, can be allocated in any scope
    int array[5] = {11,2,3,5,6};
    int (*a)[5] = &array;
    
    // compound literal, fixed size, can be allocated in any scope
    int (*b)[5] = &(int[5]){11,2,3,5,6};
    
    // dynamically allocated array, variable size possible
    int (*c)[n] = malloc( sizeof(int[n]) );
    
    // variable-length array, variable size
    int n = 5;
    int vla[n];
    memcpy( vla, something, sizeof(int[n]) ); // always initialized in run-time
    int (*d)[n] = &vla;
    
    0 讨论(0)
提交回复
热议问题