cmultidimensional-arrayinitializationc-stringsvariable-length-array

C How to create an 2d array of characters?


So would like to create an 2D array of characters for testing purposes. Here is my code.

    const int rows = 4;
    const int columns = 6;
    //char field[rows][columns];
    //fill_field(rows,columns,field);
    char field[rows][columns] = {
                            "A BCD ",
                            "B CDA ", 
                            "C DAB ", 
                            "D ABC "
                            };

I'm getting error saying "variable-sized object may not be initialized" and "excess elements in array initializer" for every string i have typed.


Solution

  • The reason you getting an error is a siz character string is 7 characters long because the compiler adds another character containing a zero value on the end of any string. This makes the arrays storage require 7 characters not 6.

    Four ways that work. Pick the syntax you prefer... I just compiled them.

    int main()
        {
            char field[4][6] = {
                                   {'A',' ','B','C','D',' '},
                                   {'B',' ','C','D','A',' '},
                                   {'C',' ','D','A','B',' '},
                                   {'D',' ','A','B','C',' '},
            };
        
            char fieldWithNulls[4][7] = {
                                   {'A',' ','B','C','D',' ', 0},
                                   {'B',' ','C','D','A',' ', 0},
                                   {'C',' ','D','A','B',' ', 0},
                                   {'D',' ','A','B','C',' ', 0},
            };
    
            char fieldWithNullsAndStrings[][7] = {
                              {"A BCD "},
                              {"B CDA "},
                              {"C DAB "},
                              {"D ABC "},
            };
    
           char fieldWithNullsAndStrings2[][7] = {
                          "A BCD ",
                          "B CDA ",
                          "C DAB ",
                          "D ABC ",
           };
        }
    

    Obviously you can tweak these how you want. The question doesn't really say what all the requirements are just that what he is doing doesn't work.

    Also you can drop the first array size as the compiler can work it out given the column size, like:

    char fieldWithNulls[][7] = {
    

    The last three arrays contain a zero terminator so can be treated as c strings. They also are identical in memory once compiled. Choose the syntax you prefer for what you are doing.