# Thread: Allocating matrices

1. ## Allocating 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]=...```

2. 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?

3. >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.

4. Ok thanks than

5. ## Got 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;```
The cout never occur!!!

6. >*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);```
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.

7. 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!!!!!!

8. >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.

9. Understood!!! Thanks again!!!

Popular pages Recent additions