2012-03-09 55 views
0

打印出我的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]每次程序運行時似乎總是有不同的字符。

+0

那些是 「行」 和 「列」 的實際變量? (定義爲int行)。如果是這樣,這甚至不應該編譯你正在使用什麼編譯器? – 2012-03-09 05:24:40

回答

1

2個問題。首先,您的陣列未初始化,您希望它具有空格。所以在開始放置邊框之前用空格填充它。

其次,你用來填充邊界的循環每個都停止2個元素的短路,例如,

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

應該是:

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

謝謝!有時你需要另一雙眼睛! – DomX23 2012-03-09 05:42:21