# Thread: quick question about creating a matrix using the new operator

1. ## quick question about creating a matrix using the new operator

Hi@all

Please can anyone tell me why when I run this program, I am getting memory fault error..

Code:
```      1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5
6
7         int** M;
8          M= new int* [5];
9         for(int i=0; i<5; i++)
10
11                 for(int j=0; j<5; j++)
12                 M[i][j]=5;
13
14
15         for(int k=0; k<5; k++)
16                 for(int m=0; m<5; m++)
17                         cout<<M[k][m];
18          return 0;
19 }```

2. Because you write in memory you didn't allocate.
Probably this is what you want. Notice the difference?
Code:
```#include<iostream>
using namespace std;

int main()
{
int i,j;
int** M;
M= new int* [5];
for(i=0; i<5; i++)
M[i]= new int [5];

for(i=0; i<5; i++)
for(j=0; j<5; j++)
M[i][j]=5;

for(int k=0; k<5; k++,cout<<endl)
for(int m=0; m<5; m++)
cout<<M[k][m]<<" ";

return 0;
}```
- Micko

3. This line:

M= new int* [5]

creates an array filled with int pointers:

[int*, int*, int*, int*, int*]

There are five elements, and you can access each element like this:

M[0], M[1], M[2], etc.

Now, what is M[0][2]? M is a single dimensional array, so there is no second index.

What you need to do is dynamically create 5 arrays of type int and assign each one to a pointer in M[]. After you do that, the notation M[0][1] will first access the pointer at index position 0 in M[]:

(M[0]) [1]

and since M[0] points to an array of ints, the second index specified will access the int at position 1:

(M[0]) [1]

4. And don't forget to free your memory up afterwards using delete [].