Hello,
i've a question: how can I get the access to all the elements of a dynamic matrix?
I create a dynamic matrix in this way:
Cout<<"insert matrix dimensions";
cin>>n;
int ** matrix= new int * [n];
for (int i=0;i<n;i++)
matrix [n]= new int [n];
//but when I try to initialize the element in this way:
for (int i=0;i<n;i++)
for (int J=0;j<n;j++)
matrix [i]*[j]=0;
the program gives me an error, how could I insert and modify all the location of the dynamic matrix?
Note, you'll need to clean up that memory. Consider defining your matrix as a std::vector<std::vector<int>> instead, or with a boost::multi_array<int, 2>.
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Inserisci le dimensioni della matrice NxN\n";
cin>>n;
int **matrix = new int * [n];
for (int i=0;i<n;i++)
matrix[n]=new int [n];
for (int i=0;i<n;i++)
for(int j=0;j<n;j++)
------> matrix [i][j]=0;
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<matrix [i][j];
cout<<endl;
}
delete []matrix[n];
return 0;
}
Please take a look at this alternative to your code:
Code:
int main()
{
int n;
cout<<"Inserisci le dimensioni della matrice NxN\n";
cin>>n;
// Create row pointers
int **matrix = new int * [n];
// Create the data for the matrix in one call.
int *matrix_data = new int[n*n];
// Create n*n matrix
for (int i=0; i < n; i++, matrix_data+=n)
matrix[i] = matrix_data; // point row pointers to matrix data
// delete n*n matrix
delete []matrix[0]; // delete the beginning of the matrix data
delete [] matrix; // delete the row pointers.
}
Compare this with your code. Hopefully you see the major difference in how the matrix is created.
In your version, you are calling new[]/delete[] n+1 times, while in the code above, there are only 2 calls, regardless of the size of the matrix. If n were 1000, you would be calling the allocator 1001 times, while the version above only calls it 2 times.
Basically this method:
1) saves time (since the allocator is only being called twice for new[] and delete[]),
2) Memory fragmentation is minimized
3) The resulting matrix has the same layout as a regular 2 dimensional array, in other words, the data is contiguous.
It works! Thank you, and thanks for the new way of creating dynamic matrix (more efficient). This is the best programming forum i've ever seen. Thank you again
Bookmarks