C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic 2D array (integer matrix) using pointer to pointer and returning it from a function

C Program: Dynamic 2D array (integer matrix) using pointer to pointer and returning it from a function

C

#include <stdio.h>

#include <stdlib.h>

 

// Function to create a dynamic 2D array and return pointer-to-pointer

int **createMatrix(int rows, int cols) {

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

    if (matrix == NULL) {

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

        exit(1);

    }

 

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

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

        if (matrix[i] == NULL) {

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

            exit(1);

        }

    }

 

    printf("\nEnter elements for %d x %d matrix:\n", rows, cols);

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

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

            printf("Element [%d][%d]: ", i, j);

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

        }

    }

 

    return matrix;  // Return pointer to matrix

}

 

// Function to display matrix

void displayMatrix(int **matrix, int rows, int cols) {

    printf("\nMatrix:\n");

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

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

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

        }

        printf("\n");

    }

}

 

// Function to free allocated memory

void freeMatrix(int **matrix, int rows) {

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

        free(matrix[i]);

    }

    free(matrix);

    printf("\nMemory freed successfully.\n");

}

 

int main() {

    int rows, cols;

    int **matrix;

 

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    matrix = createMatrix(rows, cols);  // Function returns 2D array pointer

 

    displayMatrix(matrix, rows, cols);

 

    freeMatrix(matrix, rows);

 

    return 0;

}

Output

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

Enter elements for 2 x 3 matrix:
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6

Matrix:
1   2   3
4   5   6

Memory freed successfully.

Explanation

Step

Description

1

createMatrix() dynamically allocates memory for a 2D array using malloc() and returns int **.

2

Memory is allocated for both rows and columns.

3

The function displayMatrix() prints the 2D matrix neatly.

4

freeMatrix() properly deallocates memory to prevent leaks.

5

The main function calls all three to demonstrate full use.