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
429 views
in Technique[技术] by (71.8m points)

c - Array of pointers to an array of fixed size

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*** C = {&A, &B};

This code compiles with the following warning:

warning: initialization from incompatible pointer type [enabled by default]

If I run the code, it will raise a segmentation fault. However, if I dynamically allocate A and B, it works just fine. Why is this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

...