I forgot how to allocate dynamic matrices! How can I do it??
Code:int **matrix;
matrix = new ...
for(int i...)
for(int j...)
matrix[i][j]=...
Printable View
I forgot how to allocate dynamic matrices! How can I do it??
Code:int **matrix;
matrix = new ...
for(int i...)
for(int j...)
matrix[i][j]=...
But the only thing I see is a matrix beeing allocated within a for. Can't I allocate all the memory that I want at once?
>Can't I allocate all the memory that I want at once?
Yes, but if you want to use array-like indexing you'll have to work a bit harder than that. You can find a number of different methods for allocating matrices through a board search even though the most common one uses loops to handle multiple dimensions.
Ok thanks than :)
Hi there! I made what I was told to do, but now I get Segmentation fault. Does anyone know why?
The cout never occur!!!Code:int **edges;
*edges = new int[num_nodes];
assert(*edges);
for(int i=0;i<num_nodes;i++)
{
edges[i] = new int[num_nodes];
}
cout << "Edges generated" << endl;
>*edges = new int[num_nodes];
*edges doesn't point to anything. Never dereference until you have something to reference. Try this instead:
Also, the current standard requires new to throw an exception if it fails except when tagged with (nothrow). If you have a compiler that conforms to this then the assert is useless.Code:edges = new int*[num_nodes];
assert(edges != 0);
THANKS SO MUCH!! IT WORKED(of course!)!!!
Now, just one more question: Do I still need the for to allocate the matrix? I've never see this way of allocating before!!!!!!
>Do I still need the for to allocate the matrix?
Yes. You're using a pointer to a pointer here so you'll need to allocate first an array of pointers, then allocate memory to each of the pointers in the array. Then you'll have a matrix.
Understood!!! Thanks again!!!