I’m getting some weird values when printing out the contents of my 2D array.
The contents of row and column are set by the user. In this case both are 4.
Below is my code where the board is created and assigned border outlines using * and the rows and columns have an extra 2 elements for the border.
int rows;
int columns;
while(!(file.eof()){
file >> rows >> columns;
}
char board [rows+2][columns+2];
//Set the top row border
for(int a=0; a<columns; a++){
board[0][a]='*';
}
//Set the left border
for(int a=0; a<rows; a++){
board[a][0]='*';
}
//Set the right border
for(int a=0; a<rows; a++){
board[a][columns+1]='*';
}
//Set the bottom border
for(int a=0; a<columns; a++){
board[rows+1][a]='*';
}
for(int z=0; z<rows+2; z++){
for(int x=0; x<columns+2; x++){
cout << board[z][x];
}
cout << endl;
}
for(int z=0; z<rows+2; z++){
for(int x=0; x<columns+2; x++){
cout << "[" << z << "][" << x << "]: " << board[z][x] <<endl;
}
}
Here’s the output:
****?*
*`
?*
**
**
****Qk
[0][0]: *
[0][1]: *
[0][2]: *
[0][3]: *
[0][4]: ?
[0][5]: *
[1][0]: *
[1][1]:
[1][2]: `
[1][3]:
[1][4]: ?
[1][5]: *
[2][0]: *
[2][1]:
[2][2]:
[2][3]:
[2][4]:
[2][5]: *
[3][0]: *
[3][1]:
[3][2]:
[3][3]:
[3][4]:
[3][5]: *
[4][0]:
[4][1]:
[4][2]:
[4][3]:
[4][4]:
[4][5]:
[5][0]: *
[5][1]: *
[5][2]: *
[5][3]: *
[5][4]: Q
[5][5]: k
While it should be printing:
******
* *
* *
* *
* *
******
So I’m not sure what’s going on and why the last two elements [5][4] and [5][5] always seem to have a different character assigned each time the program is being run.
2 problems. First, your array is uninitialized, where you want it to have spaces. So fill it with spaces before you start putting the borders.
Second, the loops you use for filling the borders are each stopping 2 elements short, e.g.
Should be: