Dynamic 2D Array
Completed
Read r and c, allocate a matrix as one block of r * c ints, fill it with i * c + j, and print it. Index it as m[i * c + j].
Input
Two integers r c.
Output
r rows.
Example
Input
3 4
Output
0 1 2 3 4 5 6 7 8 9 10 11
Editor
C
Hints
Row i starts at offset i * c in a single block.
Solution explanation
One contiguous block is faster and simpler to free than an array of separately allocated rows.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int r, c;
scanf("%d %d", &r, &c);
int *m = malloc(r * c * sizeof(int));
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
m[i * c + j] = i * c + j;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) printf("%3d", m[i * c + j]);
printf("\n");
}
free(m);
return 0;
}