2D Dynamic Array in C

Level 5371 keystrokes

Builds a 2x3 matrix on the heap as an array of row pointers, each pointing to its own malloc'd row, and fills it with 1 to 6. It prints the rows 1 2 3 and 4 5 6, freeing each row and then the pointer array.

C code

// Matrix size: 2 rows, 3 columns
1int rows = 2, cols = 3;
// Allocates an array of row pointers (int *), one per row
2int **matrix = (int **)malloc(rows * sizeof(int *));
// Creates each row in turn
3for (int i = 0; i < rows; i++) {
// Allocates the row itself: 3 ints
4 matrix[i] = (int *)malloc(cols * sizeof(int));
5 for (int j = 0; j < cols; j++) {
// Numbers the cells 1 to 6 in row order (i * 3 + j + 1)
6 matrix[i][j] = i * cols + j + 1;
7 }
8}
9
// Prints each row, then frees it
10for (int i = 0; i < rows; i++) {
11 for (int j = 0; j < cols; j++) {
// Prints the cells of the row, each followed by a space
12 printf("%d ", matrix[i][j]);
13 }
// Ends the row: 1 2 3, then 4 5 6
14 printf("\n");
// Each row was a separate malloc, so it needs its own free
15 free(matrix[i]);
16}
// Frees the row pointer array last, after the rows it pointed to
17free(matrix);

Output

1 2 3
4 5 6
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 16
  • (× 14
  • )× 14
  • +× 10
  • *× 9
  • =× 9
  • [× 6
  • ]× 6
  • "× 4
  • {× 4

More C examples at level 5

← C typing practice