How do I correctly set up, access, and free a multidimensional array in C?

后端 未结 5 1114
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:31

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is

5条回答
  •  执笔经年
    2020-11-21 23:51

    There are at least four different ways to create or simulate a multi-dimensional array in C89.

    One is "allocate each row separately", described by Mike in his answer. It is not a multidimensional array, it merely imitates one (in particular it mimics the syntax for accessing an element). It can be useful in the case where each row has different size, so you aren't representing a matrix but rather something with a "ragged edge".

    One is "allocate a multidimensional array". It looks likes this:

    int (*rows)[NUM_ROWS][NUM_COLS] = malloc(sizeof *rows);
    ...
    free(rows);
    

    Then the syntax to access element [i,j] is (*rows)[i][j]. In C89, both NUM_COLS and NUM_ROWS must be known at compile-time. This is a true 2-D array, and rows is a pointer to it.

    One is, "allocate an array of rows". It looks like this:

    int (*rows)[NUM_COLS] = malloc(sizeof(*rows) * NUM_ROWS);
    ...
    free(rows);
    

    Then the syntax to access element [i,j] is rows[i][j]. In C89, NUM_COLS must be known at compile-time. This is a true 2-D array.

    One is, "allocate a 1-d array and pretend". It looks like this:

    int *matrix = malloc(sizeof(int) * NUM_COLS * NUM_ROWS);
    ...
    free(matrix);
    

    Then the syntax to access element [i,j] is matrix[NUM_COLS * i + j]. This (of course) is not a true 2-D array. In practice it has the same layout as one.

提交回复
热议问题