Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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] = {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading