Hello guys,
I am trying to declare a two dimensional array in C++ on runtime. For this purpose I am asking the user about how many rows and columns should be created in the array. I have written the following code for this purpose. Apparently it is working just fine. But I am asking you if you can identify any mistake or error in this code especially in the memory deallocation part. Am I correctly releasing all the memory that I first allocated at the beginning of the program. Actually my course instructor touched this topic very slightly and also unfortunately I was not able to find any clearly explained and easy to understand article on this topic online. So, I thought that it would be better to ask someone more experienced if this code is fine or not. Also if you can think of any better way of doing any of the steps in this program then please let me know. I shall be very thankful to you.
#include <iostream>
using namespace std;
int main()
{
int cols, rows;
cout << "How many rows do you need in your matrix? ";
cin >> rows;
cout << "And ... How many columns? ";
cin >> cols;
//...............memory allocation..................//
int **myMatrix;
myMatrix = new int*[rows];
for (int i=0; i<rows; i++)
myMatrix[i] = new int[cols];
//..................................................//
//............................Input..............................//
cout << "Now fill up your " << rows << "x" << cols << " matrix:\n";
for (int i=0; i< rows; i++)
for (int j=0; j<cols; j++)
cin >> myMatrix[i][j];
//...............................................................//
//............................Output.............................//
cout << "\nYou entered the following matrix\n";
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
cout << myMatrix[i][j] << " ";
cout << endl;
}
//...............................................................//
//.................memory deallocation..............//
for (int i=0; i<rows; i++)
delete [] myMatrix[i];
delete [] myMatrix;
//..................................................//
system("pause");
return 0;
}