Case 1 :-
int* M;
M = (int*)malloc(n * n * sizeof(int));
Here memory is allocated for M
which is single pointer. Let's say you want to store 5
integers into that memory. So it looks like
-------------------------------
| 10 | 20 | 30 | 40 | 50 |
-------------------------------
M M[0] M[1] M[2] m[3] M[4] <--- Its a 1D array, only one row of 5 int
Case 2 :-
int **M;
M = malloc(n * n * sizeof(int));
M[0][0] M[0][1]
| | | | ....... | | <---- If below one is not done then how will you store the numbers into these
----------- ----- ---------
| | | |
M[0] M[1] M[2] .... M[4] <--- didn't allocated memory for these rows or 1D array
| | | |
-----------------------------------
|
M <---- allocated memory for this
It doesn't work because M
is double pointer and you allocated memory only for M
, you didn't allocated memory for M[row]
. thats why below statement didn't work.
scanf ("%d", &M[i][j]);
So to make it work first Allocate the memory for M
as you did
M = malloc(row*sizeof(*M)); /* row indicates no of rows */
and then allocate for each row
for(int index = 0 ;index < row;index++) {
M[index] = malloc(col * sizeof(*M[index])); /* col indicates number of columns */
}
And scan the matrix input
for(int index = 0 ;index < row;index++) {
for(int sub_index = 0 ;sub_index < col; sub_index++)
scanf("%d",&M[index][sub_index]);
}
and once work is done with matrix free the dynamically allocated memory using free()
for each row to avoid memory leakage.