C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Matrix addition using dynamic memory

C Program: Matrix addition using dynamic memory

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int **A, **B, **Sum;

    int rows, cols, 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 matrices A, B, and Sum

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

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

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

 

    if (A == NULL || B == NULL || Sum == NULL) {

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

        return 1;

    }

 

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

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

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

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

 

        if (A[i] == NULL || B[i] == NULL || Sum[i] == NULL) {

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

            return 1;

        }

    }

 

    // Step 3: Input matrix A

    printf("\nEnter elements of Matrix A:\n");

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

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

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

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

        }

    }

 

    // Step 4: Input matrix B

    printf("\nEnter elements of Matrix B:\n");

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

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

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

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

        }

    }

 

    // Step 5: Calculate Sum = A + B

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

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

            Sum[i][j] = A[i][j] + B[i][j];

        }

    }

 

    // Step 6: Display Resultant Matrix

    printf("\nResultant Matrix (A + B):\n");

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

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

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

        }

        printf("\n");

    }

 

    // Step 7: Free allocated memory

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

        free(A[i]);

        free(B[i]);

        free(Sum[i]);

    }

    free(A);

    free(B);

    free(Sum);

 

    return 0;

}

Output

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

Enter elements of Matrix A:
A[0][0] = 1
A[0][1] = 2
A[0][2] = 3
A[1][0] = 4
A[1][1] = 5
A[1][2] = 6

Enter elements of Matrix B:
B[0][0] = 6
B[0][1] = 5
B[0][2] = 4
B[1][0] = 3
B[1][1] = 2
B[1][2] = 1

Resultant Matrix (A + B):
7   7   7   
7   7   7

Explanation

Step

Description

malloc()

Dynamically allocates memory for 2D matrices A, B, and Sum.

Nested loops

Used to input, add, and display matrices.

Sum[i][j] = A[i][j] + B[i][j]

Performs element-wise addition.

free()

Frees all allocated memory to prevent memory leaks.