C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic 2D array (pointer-to-pointer)

C Program: Dynamic 2D array (pointer-to-pointer)

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int **arr;

    int rows, cols;

 

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    // Allocate memory for row pointers

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

    if (arr == NULL) {

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

        return 1;

    }

 

    // Allocate memory for each row

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

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

        if (arr[i] == NULL) {

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

            return 1;

        }

    }

 

    // Input elements

    printf("\nEnter elements of %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", &arr[i][j]);

        }

    }

 

    // Display matrix

    printf("\nMatrix:\n");

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

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

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

        }

        printf("\n");

    }

 

    // Free allocated memory

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

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

    }

    free(arr);  // Free row pointer array

 

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

 

    return 0;

}

Output

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

Enter elements of 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

Allocate memory for rows number of int pointers (int **arr = malloc(rows * sizeof(int *)))

2

For each row, allocate memory for columns (arr[i] = malloc(cols * sizeof(int)))

3

Use nested loops for input and display.

4

Free memory: First free each arr[i], then free arr.