Reputation: 29
I'm just a beginner with C language.
I want to determine elements of array, but it failed. I'd like to insert index(row=x, column=y). Is this possible?
Here's my code.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main(void)
{
int x, y;
char coords[3][3] = { NULL };
printf("x, y: ");
scanf("%d %d", &x, &y);
coords[x][y] = 'O';
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
printf("%c ", coords[i][j]);
printf("\n");
}
return 0;
}
If x=2, y=2, I expect the outcome to be printed
␠␠␠
␠␠␠
␠␠O
(Where ␠ is a space)
I think coords[x][y] = 'O';
is the problem, but i can't fix it.
Upvotes: 1
Views: 85
Reputation: 142025
First:
char coords[3][3] = { NULL };
The NULL
makes little sense in here, although the compiler will most probably compile the code and initialize all elements to zero. Let's fix it to something more "correct":
char coords[3][3] = { { 0 } };
The array elements not initialized explicitly are initialized to 0
. For a reference, you could read array initialization on cppreference.
Now we know that all out array elements are initialized with 0
. So you can check them before printing:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (coords[i][j] == 0) {
printf(" ");
} else {
printf("%c", coords[i][j]);
}
printf(" ");
}
printf("\n");
}
Alternatively, you could initialize all array elements to ' '
character as suggested in the other answer.
Upvotes: 2
Reputation: 51905
You have not initialized your coords
array as you perhaps think! The line:
char coords[3][3] = { NULL };
actually gives all 9 elements the value of zero - which is the nul
(unprintable) character. (If there are less initializers in the list than array elements, all 'extra' elements will be given the value of zero.)
What you perhaps want (to set all 9 elements to the blank space) is:
char coords[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
Or something similar, like using the ASCII
value for the space (32) if you know your system uses ASCII
encoding (which it is not obliged to).
Better would be to define your desired initial value as a constant, then use that as the initializer:
const char X = ' ';
char coords[3][3] = { {X, X, X}, {X, X, X}, {X, X, X} };
as this makes it easier to change things (less typing) if you need to use a different initial character.
Upvotes: 3