Reputation: 3
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
Upvotes: 0
Views: 120
Reputation: 2156
There's a type mis-match in the printf
call. You're printing maze[i][j]
, which is a char *
(string), as a character (%c
). I suggest turning on compiler warnings to catch these kinds of errors; gcc found the issue when I tried to compile your code.
The reason it prints a number instead of a character is because printf
is interpreting the address of the string maze[i][j]
as an ASCII code point and printing the corresponding character. For you compiler, the addresses of "#"
and "."
happen to result in the characters 0
and 2
being printed. It was different in my case; when I compiled your code, the program printed EOT and ACK.
The nicest solution would be to declare maze
as an array of char
s instead of strings.
char maze[4][4] = {
{ '#', '#', '#', '#' },
{ '.', '.', '.', '.' },
{ '#', '.', '.', '#' },
{ '#', '#', '#', '#' }
};
Upvotes: 1
Reputation: 145919
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.
Upvotes: 6
Reputation: 5093
The problem lies in this line
printf("%c",maze[i][j]);
you are not using characters, but char pointers (aka strings) so this should go like:
printf("%s",maze[i][j]);
Or you can also use characters instead as described in other answer.
Upvotes: 5