Max Carter
Max Carter

Reputation: 1

C Multidimensional Array: Am I missing something?

I'm currently learning C, and I have just written a draft of a program that allows a user to move a player around a character-based maze/path. I have built the maze/path as multidimensional character array, with a while loop controlling the player's position by replacing certain characters in the array. Here is the multidimensional array I have initialised:

char maze[5][7] = {
    {"_", "_", "_", "_", "_"},
    {"|", " ", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", " ", "|", "_", "|"},
    {"|", "_", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", "_", "_", "_", "|"}
};

However, when I try to compile, I get this error:

error: '}' expected

The first row in the array is apparently missing some sort of closing bracket, although I have checked proper array syntax multiple times and this appears to be correct. What am I missing? Are there any other issues with this?

Upvotes: 0

Views: 78

Answers (3)

Vishwajeet Vishu
Vishwajeet Vishu

Reputation: 492

You are giving wrong dimensions to the array maze[5][7] it is row and column and you definition says 7rows and 5 columns. And you are entering every element as an string. It should be a character which is given inside single quote like this 'a'. If you will define in double quote it will become string. This will solve your problem

char maze[7][5] = {
{'_', '_', '_', '_', '_'},
{'|', ' ', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', ' ', '|', '_', '|'},
{'|', '_', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', '_', '_', '_', '|'}
};

Hope this Helps :)

Upvotes: 0

Chris
Chris

Reputation: 11

You need to replace " with ' because a char is a single sign. The second problem is, that you assign the length wrong.

Replace the first with the second length.

char maze[7][5] = {
    {'_', '_', '_', '_', '_'},
    {'|', ' ', ' ', ' ', '|'},
    {'|', ' ', '|', ' ', '|'},
    {'|', ' ', '|', '_', '|'},
    {'|', '_', ' ', ' ', '|'},
    {'|', ' ', '|', ' ', '|'},
    {'|', '_', '_', '_', '|'}
};

Upvotes: 0

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

Your array is of type char, but your entries are of type char *. Replace double quotes " with single quotes '.

Single quotes represent char itself where double quotes represent char sequence (string) therefore compiler will try to add \0 character to the end.

On the other hand, you have to swap values 5 and 7 for initialization.

End result is similar to this:

//7 big entries with 5 values
char maze[7][5] = {
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
};

Upvotes: 1

Related Questions