Allocate memory for 2D array dynamically

Question:

Please implement it in C - To allocate memory for real 2D array dynamically, be reminded to insert your code based on the comments below accordingly.
1
#include <stdlib.h>
2
​
3
int main(void){
4
​
5
int **a, m = 500, n = 400, 1, j;
6
// Allocate memory for a[m][n] here
7
// Insert your code:
8
​
9
​
10
​
11
​
12
​
13
for ( i = 0; i < m; i++){
14
for (j = 0; j < n; j++){
15
a[i][j] = i+j;
16
}
17
}
18
return 0;
19
}
Copied!

Answer:

1
#include <stdio.h>
2
#include <stdlib.h>
3
​
4
​
5
int main(void){
6
​
7
int **a, m = 500, n = 400, i, j;
8
// Allocate memory for a[m][n] here
9
// Insert your code:
10
​
11
​
12
a = (int**) malloc(m * sizeof(int*));
13
for(int k = 0; k < m; k++){
14
a[k] = (int*) malloc (n * sizeof(int));
15
​
16
}
17
​
18
​
19
for ( i = 0; i < m; i++){
20
for (j = 0; j < n; j++){
21
a[i][j] = i+j;
22
}
23
}
24
​
25
for ( int k = 0; k < m; k++){
26
for (int r = 0; r < n; r++){
27
printf("a[%d][%d] = %d \n", k, r, a[k][r]);
28
}
29
}
30
31
for (int t = 0; t < m; t++)
32
free(a[t]);
33
34
free(a);
35
36
return 0;
37
}
38
​
Copied!
Copy link
Contents
Question: