Array of pointers to an array of fixed size

后端 未结 9 1785
心在旅途
心在旅途 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:27

    Arrays are not the same thing as multi-dimensional pointers in C. The name of the array gets interpreted as the address of the buffer that contains it in most cases, regardless of how you index it. If A is declared as int A[5][5], then A will usually mean the address of the first element, i.e., it is interpreted effectively as an int * (actually int *[5]), not an int ** at all. The computation of the address just happens to require two elements: A[x][y] = A + x + 5 * y. This is a convenience for doing A[x + 5 * y], it does not promote A to multidimensional buffer.

    If you want multi-dimensional pointers in C, you can do that too. The syntax would be very similar, but it requires a bit more set up. There are a couple of common ways of doing it.

    With a single buffer:

    int **A = malloc(5 * sizeof(int *));
    A[0] = malloc(5 * 5 * sizeof(int));
    int i;
    for(i = 1; i < 5; i++) {
        A[i] = A[0] + 5 * i;
    }
    

    With a separate buffer for each row:

    int **A = malloc(5 * sizeof(int *));
    int i;
    for(i = 0; i < 5; i++) {
        A[i] = malloc(5 * sizeof(int));
    }
    

提交回复
热议问题