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];
    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 :

two ways that work. 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},

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] = {

Leave a Reply