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

后端 未结 5 2056
一整个雨季
一整个雨季 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:04

    Not a direct answer to those questions in the original post, I just want to point out that what the asker propose may be not such a good or useful idea.


    The compiler indeed can infer from

    int multi_array[][] = {
      {1,2,3,4,5},
      {10,20,30,40,50},
      {100,200,300,400,500}
    };
    

    the structure of multi_array.

    But when you want to declare and define a function (this declaration and definition could be in another compilation unit or source file) that supposes to accept multi_array as one of its argument, you still need to do something like

    int foo(..., int multi_array[][COL], ...) { }
    

    Compiler needs this COL to do proper pointer arithmetic in foo().

    Usually, we define COL as a macro that will be replaced by an integer in a header file, and use it in the definitions of multi_array and foo():

    int multi_array[][COL] = { ... };
    
    int foo(..., int multi_array[][COL], ...) { }
    

    By doing this, it is easy to make sure they are the same. And let compiler to infer the structure of multi_array according to its initialization, when you give it a wrong initialization, you actually introduce a bug in your code.

提交回复
热议问题