打印数组内容时出现奇怪的值

Weird values when printing contents of array

本文关键字:数组 打印      更新时间:2023-10-16

当打印出2D数组的内容时,我得到了一些奇怪的值。

行和列的内容由用户设置。在这种情况下,两者都是4。

下面是我的代码,其中使用*创建并分配了板的边框轮廓,行和列的边框有额外的2个元素。

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;
    }
}

这是输出:

****?*
*`
  ?*
**
**
****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

当它应该打印时:

******
*    * 
*    *
*    * 
*    * 
****** 

所以我不知道发生了什么,也不知道为什么最后两个元素[5][4]和[5][5]在每次运行程序时似乎总是分配不同的字符。

2个问题。首先,您的数组未初始化,您希望它在其中有空格。因此,在开始设置边界之前,请先填充空格。

第二,你用来填充边界的循环每个都有两个短元素,例如

for(int a=0; a<rows; a++)

应为:

for(int a=0; a<rows+2; a++)