C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY
Create a Dynamic Two-Dimensional Array
Learn how to create a dynamic two-dimensional array using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
2 2 1 2 3 4
Sample output
Sum = 10
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t rows, columns;
printf("Enter rows and columns: ");
scanf("%zu %zu", &rows, &columns);
int **matrix = malloc(rows * sizeof *matrix);
if (matrix == NULL) return 1;
for (size_t row = 0; row < rows; row++) {
matrix[row] = malloc(columns * sizeof *matrix[row]);
if (matrix[row] == NULL) {
while (row > 0) free(matrix[--row]);
free(matrix);
return 1;
}
}
int sum = 0;
printf("Enter matrix elements: ");
for (size_t row = 0; row < rows; row++)
for (size_t column = 0; column < columns; column++) {
scanf("%d", &matrix[row][column]);
sum += matrix[row][column];
}
printf("Sum = %d\n", sum);
for (size_t row = 0; row < rows; row++) free(matrix[row]);
free(matrix);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 10
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Allocate an array of row pointers, allocate every row, use the matrix, and free every allocation.
- Display the computed result.
Allocate an array of row pointers, allocate every row, use the matrix, and free every allocation.
EFFICIENCY
Time and space complexity
Time complexity
O(rows × columns)
Auxiliary space
O(rows × columns)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
