我是 C++ 的初学者,我不明白为什么我不能制作这种 while 循环:
#include <iostream>
using namespace std;
const int gridRows = 3;
const int gridColumns = 3;
string **grid = new string *[gridRows];
int main()
{
void InitGrid(string **, const int &, const int &);
void CleanGrid(string **, const int &, const int &);
while (true)
{
InitGrid(grid, gridRows, gridColumns);
//some code
CleanGrid(grid, gridRows, gridColumns);
}
return 0;
}
void InitGrid(string **grid, const int &rows, const int &columns)
{
for (int i = 0; i < rows; i++)
{
grid[i] = new string[columns];
for (int j = 0; j < columns; j++)
{
grid[i][j] = "[ ]";
}
}
}
void CleanGrid(string **grid, const int &rows, const int &columns)
{
for (int i = 0; i < rows; i++)
{
delete[] grid[i];
}
delete[] grid;
}
我希望有人能够帮助我^^ Thx。
如果我删除双指针的动态分配,我的代码将正确循环。我想我们不能在 while 循环中动态分配,但我认为这很奇怪,我肯定错过了一些东西......
让我们来看看...
string **grid = new string *[gridRows];
全局变量
grid
被初始化为指向动态分配的指向std::string
的指针数组的第一个元素。
您致电
InitGrid
这会...
grid[i] = new string[columns];
它分配字符串数组,并将指向该数组第一个元素的指针分配给
grid
指向的数组元素。它还为字符串分配了一些东西,但这并不重要。
接下来你调用
CleanGrid
,它会:
for (int i = 0; i < rows; i++)
{
delete[] grid[i];
}
它会删除
InitGrid
分配的内容。它将数组删除为字符串。但是,现在糟糕的是,它还删除了数组:
delete[] grid;
这并不是全部被
InitGrid
覆盖。它是在初始化 grid
时分配的。
下次您调用
InitGrid
时,它将尝试写入不再存在的数组,因为您刚刚删除了它。
请勿使用生的
new
和 delete
。也不要使用原始拥有指针。
您的代码不需要任何这些。使用
std::vector
来动态调整大小的数组。