I'm writing a program to play battleship. I have a string matrix representing the battlefield.
#define NUM_CASELLE 6
char* campo[NUM_CASELLE][NUM_CASELLE];
At the beginning of the program each element of the matrix is initialized with "-".
I noticed that I have problems accessing the matrix elements so I did some debugging to better understand what the problem was and I noticed this: if I write
printf("The content is %s\n", campo[3][1]);
the result is
The content is -
and that's right.
But if I enter coordinates from stdin and memorize them in variables,
printf("row is %c\n", row);
printf("col is %d\n", col);
printf("The content is %s\n", campo[row][col]);
the result is as follows:
The content is (null)
Where am I wrong?
Anyway, I post the whole code because maybe the error is elsewhere. In fact, the coordinates are entered as they are in battleship, for example, a3 or b5 or f1 etc .. and then I convert the letter to the respective row index.
#define NUM_CASELLE 6
#define NUM_NAVI 7
int pos_size = 256;
char* campo[NUM_CASELLE][NUM_CASELLE];
void posizionaNavi(){
char pos[pos_size];
int i = 0;
int col;
int row;
printf("Scegli dove posizionare le navi...\n");
while(i < NUM_NAVI){
printf("Posizionare nave numero %d...\n", i + 1);
fgets(pos, pos_size, stdin);
col = isCommandValid(pos);
row = pos[1];
if(col == -1){
printf("\n");
printf(">> ATTENZIONE: formato errato.\n");
printf(">> Le colonne vanno dalla lettera A alla lettera F\n");
printf(">> Le righe vanno dal numero 1 al numero 6\n");
printf(">> Esempi di comando valido: a3 - b6 - f1\n");
printf("\n");
}
else{
printf("row is %c\n", row);
printf("col is %d\n", col);
printf("The content is %s\n", campo[row][col]);
printf("The content is %s\n", campo[3][1]);
if(campo[row][col] = " - "){
campo[row][col] = " x ";
printf("Nave %d posizionata in %s\n", i + 1, pos);
i++;
}
else{
printf(">> ATTENZIONE: casella già occupata da una nave.");
printf(">> Riprovare...\n");
printf("\n");
}
}
}
}
int isCommandValid(char* pos){
int ret;
if(strlen(pos) != 3 || pos[1] > '6' || pos[1] < '1')
return -1;
switch(pos[0]){
case 'a':
ret = 1;
break;
case 'A':
ret = 1;
break;
case 'b':
ret = 2;
break;
case 'B':
ret = 2;
break;
case 'c':
ret = 3;
break;
case 'C':
ret = 3;
break;
case 'd':
ret = 4;
break;
case 'D':
ret = 4;
break;
case 'e':
ret = 5;
break;
case 'E':
ret = 5;
break;
case 'f':
ret = 6;
break;
case 'F':
ret = 6;
break;
default:
ret = -1;
break;
}
return ret;
}