Search code examples
carraysmaze

C character array printing numbers insted of the assigned charaters


I am working on an assignment to solve a maze created from a 2d character array. To test the program I made a simple 4x4 maze. But the maze, when printed to the screen is comprised of numbers. I am very confused at how this even happens. Any help would be appreciated.

The assignment is this:

char *maze[4][4];
for (int i=0; i < 4; ++i)
{
    maze[0][i] = "#";
    maze[3][i] = "#";
    maze[1][i] = ".";
}
maze[2][0] = "#";
maze[2][3] = "#";
maze[2][1] = ".";
maze[2][2] = ".";

and printing is here:

for(int i =0; i < 4; ++i)
{
    for(int j = 0; j < 4; ++j)
    {
        printf("%c",maze[i][j]);
    }
    printf("\n");
}

I expected it to print this:

####
....
#..#
####

But instead it prints:

0000
2222
0220
0000

Solution

  • maze[0][i] = "#";
    

    should be

    maze[0][i] = '#';
    

    and char *maze[4][4]; should be char maze[4][4];

    "#" is a string literal, use '#' to have a character constant.

    If you really want to use string literals of one character you have to use the %s conversion specification instead of %c in your original program.