C Program: Dynamic 2D Array & Transpose
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a 2D Array and Calculate the Transpose of the Matrix

๐Ÿ“‘ On this page:
  • Purpose & Objective
  • What is a Matrix Transpose?
  • Real-Life Applications
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
๐Ÿ“š In this program, you will learn:
  • How to allocate a 2D array (pointer-to-pointer) at runtime with malloc()
  • How to allocate each row separately and check for NULL on every allocation
  • How to read a matrix from the user with nested loops
  • How to compute the transpose by swapping row and column indices
  • How to free a 2D array correctly โ€” row by row, then the outer pointer

Purpose & Objective

Purpose: The motive of this C program is to illustrate dynamic memory allocation for a 2D array and compute its transpose.

Objective:

  • Allocate memory dynamically for a 2D array based on user input for dimensions.
  • Compute the transpose of the matrix in which rows and columns are swapped.
  • Illustrate memory control, pointer usage, and matrix operations in C programming.

๐Ÿ’ก Quick Definition: The transpose of a matrix is obtained by swapping its rows and columns โ€” the element at row i, column j moves to row j, column i. An m ร— n matrix becomes an n ร— m matrix.

C program to dynamically allocate memory for a 2D array and calculate the transpose of the matrix

What is a Matrix Transpose?

If A is a matrix with m rows and n columns, its transpose Aแต€ has n rows and m columns. The element that was at A[i][j] moves to Aแต€[j][i].

Matrix Dimensions Example
Original Am ร— n1 2 3
4 5 6
7 8 9
Transpose Aแต€n ร— m1 4 7
2 5 8
3 6 9

Real-Life Applications

Understanding and computing matrix transposes has practical applications in several fields:

Mathematics and Computer Science

  • Transposes are used in matrix manipulations like multiplication, solving equations, and finding determinants.
  • Matrices and their transposes are vital in algorithms for graph traversal and shortest-path calculations.

Computer Graphics

  • Transposes play a role in transforming objects in 3D graphics.
  • Matrices are used in mapping object coordinates to display coordinates.

Data Analysis

  • Transposes are used in statistical computations and data manipulation.
  • Matrices and transposes are essential in machine-learning algorithms for data pre-processing and feature extraction.

Complete C Program

Program: Dynamically allocate a 2D array and calculate its transpose without using functions

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int rows, cols;
    int i, j;
    int **matrix, **transpose;

    /* Input dimensions of the matrix */
    printf("Enter number of rows and columns of the matrix: ");
    scanf("%d %d", &rows, &cols);

    /* Allocate memory for the matrix (array of row pointers) */
    matrix = (int **)malloc(rows * sizeof(int *));
    if (matrix == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    /* 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.\n");
            return 1;
        }
    }

    /* Input elements into the matrix */
    printf("Enter elements of the matrix:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    /* Print the original matrix */
    printf("The original matrix is:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    /* Allocate memory for the transpose matrix */
    transpose = (int **)malloc(cols * sizeof(int *));
    if (transpose == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    /* Allocate memory for each row of the transpose matrix */
    for (i = 0; i < cols; i++) {
        transpose[i] = (int *)malloc(rows * sizeof(int));
        if (transpose[i] == NULL) {
            printf("Memory allocation failed.\n");
            return 1;
        }
    }

    /* Compute the transpose of the matrix */
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }

    /* Print the transpose matrix */
    printf("The transpose of the matrix is:\n");
    for (i = 0; i < cols; i++) {
        for (j = 0; j < rows; j++) {
            printf("%d ", transpose[i][j]);
        }
        printf("\n");
    }

    /* Free allocated memory for both matrices */
    for (i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);

    for (i = 0; i < cols; i++) {
        free(transpose[i]);
    }
    free(transpose);

    return 0;
}
                                    

Program Output

Enter number of rows and columns of the matrix: 3 3

Enter elements of the matrix:
1 2 3
4 5 6
7 8 9

The original matrix is:
1 2 3
4 5 6
7 8 9

The transpose of the matrix is:
1 4 7
2 5 8
3 6 9
                                

Step-by-Step Explanation

Let's break down this program line by line to understand what's happening:

1. Include header files:

#include <stdio.h>
#include <stdlib.h>
                                

stdio.h provides printf/scanf. stdlib.h provides malloc/free.

2. Declare pointer-to-pointer and dimensions:

int rows, cols;
int i, j;
int **matrix, **transpose;
                                

matrix is a pointer to a pointer โ€” it points to an array of row pointers, each of which points to a block of integers. The loop counters i and j are declared up front for C89 compatibility.

3. Read dimensions:

printf("Enter number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);
                                

The number of rows and columns is read at runtime โ€” this is exactly why we need dynamic allocation.

4. Allocate the outer array of row pointers:

matrix = (int **)malloc(rows * sizeof(int *));
if (matrix == NULL) {
    printf("Memory allocation failed.\n");
    return 1;
}
                                

We request rows pointers. Each pointer will later hold the address of one row's data block.

5. Allocate each row:

for (i = 0; i < rows; i++) {
    matrix[i] = (int *)malloc(cols * sizeof(int));
    if (matrix[i] == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
}
                                

Each row is a block of cols integers. If any allocation fails, we bail out โ€” the already-allocated rows would leak in a longer program, but for a demo exit this is acceptable.

6. Read matrix elements:

for (i = 0; i < rows; i++) {
    for (j = 0; j < cols; j++) {
        scanf("%d", &matrix[i][j]);
    }
}
                                

Nested loops read each element into matrix[i][j]. Note that matrix[i][j] is exactly equivalent to *(*(matrix + i) + j).

7. Allocate the transpose matrix:

transpose = (int **)malloc(cols * sizeof(int *));
for (i = 0; i < cols; i++) {
    transpose[i] = (int *)malloc(rows * sizeof(int));
}
                                

Because a transpose swaps the dimensions, the new matrix has cols rows and rows columns. That's the reverse of the original.

8. Fill the transpose:

for (i = 0; i < rows; i++) {
    for (j = 0; j < cols; j++) {
        transpose[j][i] = matrix[i][j];
    }
}
                                

Element matrix[i][j] goes into transpose[j][i] โ€” that's the whole transpose operation.

9. Print both matrices and free memory:

for (i = 0; i < rows; i++) {
    free(matrix[i]);
}
free(matrix);

for (i = 0; i < cols; i++) {
    free(transpose[i]);
}
free(transpose);
                                

Order matters: free each row first, then the outer array. Freeing in the wrong order leaves you with dangling row pointers. This pattern must be repeated for both matrices.

๐ŸŽฏ Key Takeaway: A 2D dynamically-allocated array is really an array of pointers to arrays. Allocation and freeing both happen in two nested steps. Get the order right and you'll never leak or crash.

Frequently Asked Questions

1. Why not just use a single malloc call?

You can. A single call malloc(rows * cols * sizeof(int)) gives you a flat block โ€” but then you must compute offsets manually (arr[i * cols + j]). The pointer-to-pointer approach lets you write matrix[i][j], which is more readable.

2. What if malloc fails partway through row allocation?

The code above exits early. In production, you'd write a cleanup loop that frees the rows already allocated before returning, to avoid leaking.

3. Can I transpose in place?

Only for a square matrix (rows == cols). For non-square matrices you must allocate a new block, which is what this program does.

4. Why do we need two loops just to free memory?

Because matrix is an array of row pointers. The outer free only releases the array of pointers, not the row data blocks. Each row must be freed individually first.

๐Ÿ’ก Tip: Compile with gcc -fsanitize=address -g to catch leaks and out-of-bounds writes instantly.

๐Ÿ“– Related Tutorials

  • malloc in C
  • calloc in C
  • free in C
  • 1. Dynamic Array of Integers and Sum
  • 2. Dynamic String and Reverse In Place
  • All DMA Assignments

Previous Topic: -->> 2. Dynamic String & Reverse In Place   ||   Next topic: -->> 4. Dynamic Linked List & Reverse


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.