我有一個2維字符數組char** field
。我有一個方法get_field()
它使這個字符數組的副本,並返回此副本。額外的垃圾值外部尺寸字符陣列
char** Game::get_field() {
char** copy = new char*[this->width_field];
for (unsigned int i = 0; i < this->width_field; i++)
copy[i] = new char[this->length_field];
for (unsigned int i = 0; i < this->width_field; i++) {
for (unsigned int j = 0; j < this->length_field; j++)
copy[i][j] = this->field[i][j];
}
return copy;
}
當我將副本的值輸出到控制檯時,我在每行之後都會得到一些垃圾值。然而,char數組的每一行都包含'\ 0'字符來標記字符串的結尾。經過對調試器的一些調查後,我發現在get_field()
方法中,當聲明數組時,額外的垃圾值會增加以外的尺寸。
當length_field
等於52我得到了51破折號加上'\ 0'字符就像在圖像和之後,一些額外的垃圾值。這些垃圾值從哪裏來,我如何擺脫它們?
[編輯:] 這是做輸出到控制檯的代碼:
char** field = game->get_field();
for (unsigned int i = 0; i < 13; i++) {
cout << field[i] << endl;
}
這是代碼的初始場是如何設置:
this->field = new char*[this->width_field];
for (unsigned int i = 0; i < this->width_field; i++)
this->field[i] = new char[this->length_field];
this->setup_field();
void Game::setup_field(){
this->field[0] = "---------------------------------------------------\n\0";
this->field[1] = "| | |\n\0";
this->field[2] = "| | |\n\0";
this->field[3] = "| | |\n\0";
this->field[4] = "|---- | ----|\n\0";
this->field[5] = "| | -|- | |\n\0";
this->field[6] = "| | | | | | |\n\0";
this->field[7] = "| | -|- | |\n\0";
this->field[8] = "|---- | ----|\n\0";
this->field[9] = "| | |\n\0";
this->field[10] = "| | |\n\0";
this->field[11] = "| | |\n\0";
this->field[12] = "---------------------------------------------------\n\0";
}
首先想到的是長度和寬度你認爲他們是什麼? – Ben
是的。用調試器檢查它。 –
有趣的代碼是將數據輸出到控制檯(以及初始化它)的代碼。 – Deduplicator