1

I am trying to initialise a 2D Array in C filled with X's except for the index (2,2) which will be filled with the letter 'C'. However, when I run the code below, not only do I get a 'C' at (2,2) but for some reason, I also end up getting a 'C' at the index (1,9) (see output below).

I tried changing the width and height values and realised that it works sometimes. For example, when I make height = 10 and width = 10, I get the correct output with only one 'C' in its proper slot.

I'm quite new to C programming and have no idea why it's producing the correct output sometimes. Any help would be much appreciated!

int width = 10;
int height = 7;
int x = 2;
int y =2;
int limit = 3;

//initialising 2D array
char board[width][height];
for(int i = 0; i < height; i++){//rows
    for (int j = 0; j < width; j++){//cols
        if(i == y && j == x){
            board[y][x] = 'C';
        }
        else{
            board[i][j] = 'X';
        }
    }
}
//printing 2D array
for(int i = 0; i < height; i++){//rows
    for (int j = 0; j < width; j++){//cols
        printf("%c ", board[i][j]);
    }
    printf("\n");
}

Sample output

4
  • 1
    Since it's an array of char, you may as well just do: memset(board, 'X', width * height); board[y][x] = 'C'; Commented Mar 16, 2017 at 3:30
  • 1
    Do you just want 'C' in a few positions while the rest are 'X'? If so, memset () might be better. Use it to set all the values to 'X' then use conditionals to set specific values in the array to something else. Commented Mar 16, 2017 at 3:37
  • In the future, always copy paste the output as text. Don't use an image for displaying text. Commented Mar 16, 2017 at 3:40
  • Thanks for pro tip. Will try that :) Commented Mar 16, 2017 at 3:41

1 Answer 1

2

You got the array declaration wrong. Instead of

char board[width][height];

you need

char board[height][width];
/*          Rows    Cols  */
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh cheers mate. I knew I overlooked something simple. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.