Hi. I have a question about a program I wrote to generate a 2D "Array" with user-defined dimensions. Right now the program only asks for the dimensions, fills the elements with an ascending sequence of numbers and shows the "array". Here's the code:
Code:
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int rows;
int columns;
int i;
int j;
int counter = 1;
cout << "Rows? ";
cin >> rows;
cout << "Columns? ";
cin >> columns;
cout << endl;
int** pRows;
int* pColumns;
if (!(pRows = new int*[rows]))
{
cout << "Not enough memory. Sorry.\n";
exit(1);
}
for (i = 0; i < rows; i++, counter++)
{
if (!(pColumns = new int[columns]))
{
cout << "Not enough memory. Sorry.\n";
exit(1);
}
pRows[i] = pColumns;
for (j = 0; j < columns; j++, counter++)
{
pRows[i][j] = counter;
if (j == columns - 1) counter--;
}
}
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++)
{
cout << setw(6) << pRows[i][j];
if (j == columns - 1) cout << endl;
}
delete[] pRows;
delete[] pColumns;
return 0;
}
My question is: is it enough with the two delete instructions to free all dynamically allocated memory? I don't think so, since the pointer pColumns goes through different memory allocations inside of the for loop. How can I solve this? Or should I simply ignore the memory leaks?
Or is there any other way to create a 2D Array with user-defined dimensions?
Thanks!