C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic matrix allocation

C Program: Dynamic matrix allocation

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int **matrix;

    int rows, cols;

    int i, j;

 

    // Step 1: Input matrix dimensions

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    // Step 2: Allocate memory for row pointers

    matrix = (int**) malloc(rows * sizeof(int*));

 

    if (matrix == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

 

    // Step 3: Allocate memory for each row

    for (i = 0; i < rows; i++) {

        matrix[i] = (int*) malloc(cols * sizeof(int));

        if (matrix[i] == NULL) {

            printf("Memory allocation failed for row %d!\n", i);

            return 1;

        }

    }

 

    // Step 4: Input matrix elements

    printf("\nEnter elements of the matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("matrix[%d][%d] = ", i, j);

            scanf("%d", &matrix[i][j]);

        }

    }

 

    // Step 5: Display matrix

    printf("\nMatrix elements are:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d\t", matrix[i][j]);

        }

        printf("\n");

    }

 

    // Step 6: Free dynamically allocated memory

    for (i = 0; i < rows; i++) {

        free(matrix[i]);  // Free each row

    }

    free(matrix);  // Free row pointers

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows: 2
Enter number of columns: 3

Enter elements of the matrix:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6

Matrix elements are:
1   2   3   
4   5   6


Explanation

Step

Description

int **matrix;

Declares a pointer to a pointer (used for 2D array).

malloc(rows * sizeof(int*))

Allocates memory for row pointers.

Inner loop

Allocates memory for each row dynamically.

Nested loops

Used for taking input and displaying matrix elements.

free()

Properly frees all allocated memory row by row.