C++中用於初始化和改變使用int**
聲明的二維整數數組的正確語法是什麼?在C++中改變函數內部二維數組的值
我正在使用下面的代碼,但由於內存在函數退出時被取消分配,我得到了意外的行爲,這當然是它的意圖。
但是,這怎麼能在C++中整齊地完成呢?我知道其他人也面臨類似的問題,但Is passing pointer argument, pass by value in C++?等問題太籠統。
void Insert_into_2D_Array(int** foo, int x_pos, int y_pos, int x_size, int y_size)
{
int insert_value = 10;
if (x_pos < x_size && y_pos < y_size) {
foo[x_pos][y_pos] = insert_value; // insert_value lost post func exit?
}
}
void Init_2D_Array(int** foo, int x_size, int y_size)
{
foo = new int*[x_size]; // new alloc mem lost post func exit ?
for (int i=0;i<x_size;i++)
{
foo[i] = new int[y_size]; // new alloc mem lost post func exit
}
}
int main(int agc, char** argv)
{
int** foo;
int x_size=10, y_size=10;
Init_2D_Array(foo, x_size, y_size);
Insert_into_2D_Array(foo, 3,3, x_size, y_size);
}
當你調用'new'時,函數返回時內存不會被釋放。 – user463035818
它沒有被釋放。你只是簡單地設置了指針'foo'的值,它是通過值*傳遞的。您需要在本地聲明'foo',或者在末尾傳遞'int *** foo'並解除引用。 – meowgoesthedog
正如你所說,做'Init_2D_Array(foo)'按值傳遞它。要通過引用來傳遞它,語法應該是什麼? –