- How to allocate a 2D array (pointer-to-pointer) at runtime with
malloc() - How to allocate each row separately and check for
NULLon 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.
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 A | m ร n | 1 2 3 |
Transpose Aแต | n ร m | 1 4 7 |
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.