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

- 08-29-2003gustavosserraAllocating matrices
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]=...

- 08-29-2003gustavosserra
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?

- 08-29-2003Prelude
>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. - 08-29-2003gustavosserra
Ok thanks than :)

- 08-29-2003gustavosserraGot errors
Hi there! I made what I was told to do, but now I get Segmentation fault. Does anyone know why?

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;

- 08-29-2003Prelude
>*edges = new int[num_nodes];

*edges doesn't point to anything. Never dereference until you have something to reference. Try this instead:

Code:`edges = new int*[num_nodes];`

assert(edges != 0);

- 08-29-2003gustavosserra
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!!!!!! - 08-29-2003Prelude
>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. - 08-29-2003gustavosserra
Understood!!! Thanks again!!!