Array of pointers to an array of fixed size

后端 未结 9 1788
心在旅途
心在旅途 2020-12-14 06:04

I tried to assign two fixed-size arrays to an array of pointers to them, but the compiler warns me and I don\'t understand why.

int A[5][5];
int B[5][5];
int         


        
9条回答
  •  遥遥无期
    2020-12-14 06:31

    If you want a declaration of C that fits the existing declarations of A and B you need to do it like this:

    int A[5][5];
    int B[5][5];
    int (*C[])[5][5] = {&A, &B};
    

    The type of C is read as "C is an array of pointers to int [5][5] arrays". Since you can't assign an entire array, you need to assign a pointer to the array.

    With this declaration, (*C[0])[1][2] is accessing the same memory location as A[1][2].

    If you want cleaner syntax like C[0][1][2], then you would need to do what others have stated and allocate the memory dynamically:

    int **A;
    int **B;
    // allocate memory for A and each A[i]
    // allocate memory for B and each B[i]
    int **C[] = {A, B};
    

    You could also do this using the syntax suggested by Vlad from Moscow:

    int A[5][5];
    int B[5][5];
    int (*C[])[5] = {A, B};
    

    This declaration of C is read as "C is an array of pointers to int [5] arrays". In this case, each array element of C is of type int (*)[5], and array of type int [5][5] can decay to this type.

    Now, you can use C[0][1][2] to access the same memory location as A[1][2].

    This logic can be expanded to higher dimensions as well:

    int A[5][5][3];
    int B[5][5][3];
    int (*C[])[5][3] = {A, B};
    

提交回复
热议问题