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.

AdvancedPointer to pointermalloc()Dynamic matrix

PROBLEM UNDERSTANDING

Input and expected output

Sample input
2 2
1 2
3 4
Sample output
Sum = 10

COMPLETE C PROGRAM

Complete C implementation

dynamic-two-dimensional-array.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Sum = 10
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Allocate an array of row pointers, allocate every row, use the matrix, and free every allocation.
  3. 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.