I have referred to FAQ regarding C++ double pointers and I have written a small code to verify. Can someone have a look and let me know if I am freeing the memory correctly.
I have not put any checks for NULL in case memory is not allocated for now if someone can suggest (if possible with example for double pointers) what would be the best way. Initially I thought something like this
Code:
if(XXXXX ==NULL)
{cout<<"Error allocating memory";
exit(0);
}
However, I remember using something better like cerror or cerr (I don't remember). If anyone could throw some light on it. Thanks
Also i am thinking of requesting the moderator to put the freeing of memory in FAQ in the section addressing double pointers in C++ FAQ. Let me know if you think it's a good idea.
This is the code for putting elements in a 2d matrix
Code:
#include <iostream.h>
void main (void)
{
int **matrix,rows,columns,i,j;
cout<<"Enter the columns";
cin>>columns;
cout<<"Enter the no. of rows";
cin>>rows;
matrix = new int*[rows];
for(i=0;i<rows;i++)
{
matrix[i] = new int[columns];
}
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
{
matrix[i][j]=j+i*10;
cout<<"matrix"<<"["<<i<<"]["<<j<<"]="<<matrix[i][j]<<"\t";
}
}
for(i=0;i<rows;i++)
{
delete[] matrix[i];
}
delete[] matrix;
cout<<endl;
}