Can a two-dimensional array in C be initialized without explicit size?

后端 未结 5 2105
一整个雨季
一整个雨季 2021-01-11 13:27

I have a question regarding two-dimensional arrays in C. I know now (from direct compiler experience) that I can\'t initialize such an array analogously to one-dimensional a

5条回答
  •  情歌与酒
    2021-01-11 14:19

    You can do this using the C99 compound literal feature.

    A partial idea is that the length of an initializer list can be determined like this:

    sizeof (int[]){ 1, 2, 3, 4, 5 } / sizeof(int)
    

    We need a workaround for the fact that the only way you can pass an argument containing a comma to a macro is to put parentheses around (part of) the argument:

    #define ROW(...) { __VA_ARGS__ }
    

    Then the following macro deduces the second dimension from the first row:

    #define MAGIC_2DARRAY(type, ident, row1, ...) \
            type ident[][sizeof (type[])row1 / sizeof (type)] = { \
                    row1, __VA_ARGS__ \
            }
    

    It only works if there are at least two rows.

    Example:

    MAGIC_2DARRAY(int, arr, ROW(7, 8, 9), ROW(4, 5, 6));
    

    You probably do not want to use this in a real program, but it is possible.

    For passing this kind of array to functions, the C99 variable length array feature is useful, with a function like:

    void printarr(int rows, int columns, int array[rows][columns]) { ... }
    

    called as:

    printarr(sizeof arr / sizeof arr[0], sizeof arr[0] / sizeof arr[0][0], arr);
    

提交回复
热议问题