I'm a beginner in C++, and I don't understand why I can't make this kind of while loop :
#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;
}
I hope someone will be able to help me ^^ Thx.
If I remove the dynamic allocation of my double pointers my code loops properly. I guess we cant alloc dynamicly in a while loop but I think it's pretty strange, I'm surely missing something...
newfor everything (using naked new/delete is something only to be used inside datastructures). A fixed size grid of strings would be astd::array<std::array<std::string,3>,3>in C++. std::string itself will take care of (potential) dynamic memory allocation for you. If you have a "resizable" grid usestd::vector<std::vector<std::string>>gridis only initialised with anewexpression once (wheregridis defined, abovemain()) but it is released with adeleteexpression on every call ofCleanGrid(). The allocation of allgrid[i]s inInitGrid()would be deallocated correctly inCleanGrid()if it wasn't for the incorrect handling ofgriditself.