Dynamic Arrays and Matrices in C

Lesson 13 of 15 · C

Two-dimensional arrays – matrices are explained in the article Two-dimensional arrays – matrices, where memory is reserved statically, i.e. the dimensions m*n of the matrix do not change while the program runs. This article describes how to define memory dynamically, using pointers, so that it can be changed later.

Suppose we read a matrix of integers of size 4*3, so that these dimensions can change later. This can be done with pointers to integer data (int*), so that every row is one dynamic array pointed to by a row pointer (int * r), and the set of all rows, i.e. the matrix as a whole, is pointed to by a pointer to a pointer, e.g. (int ** A).

Defining these pointers, and therefore dynamic arrays and matrices, differs between the programming languages C and C++, as shown below.

Explaining the concept: dynamic vs. static memory allocation

1. What is memory allocation?

In C, memory can be allocated in two main ways:

✅ Statically (at compile time) – The size of the array is known in advance and is determined when the program is compiled.

✅ Dynamically (at run time) – Memory is assigned while the program runs, which allows more flexibility.

2. When to use dynamic allocation?

Comparing the properties of static and dynamic memory allocation:

Situation Static allocation Dynamic allocation
The size of the array is known in advance ✅ Yes ❌ No
The size depends on user input ❌ No ✅ Yes
Reallocation is needed while the program runs ❌ No ✅ Yes
Less complexity and more safety ✅ Yes ❌ No
Flexibility and memory optimization ❌ No ✅ Yes

Examples of when to use dynamic allocation:

  • Processing data from a file, when we do not know in advance how many rows and columns there will be.
  • The user enters the size of the matrix, so the user determines the dimensions while the program runs.
  • Efficient use of memory, so that we allocate only as much as we need.

3. Advantages of dynamic allocation

✅ Flexibility – We can create and use memory on the fly.

✅ Efficient use of memory – No unnecessary memory is wasted as with static arrays.

✅ It makes working with large data possible – Static arrays are limited by the size of the stack memory, while malloc allocates memory on the heap, where we can use bigger structures.

💡 Example: The statically allocated array int matrix[1000][1000]; may cause a stack overflow, while malloc uses heap memory, which makes working with large data possible.

4. Possible risks and how to avoid them

🔴 Memory leak

  • Problem: If we forget to free memory (free()), the program uses more and more memory without being able to get it back.
  • Solution: Always use free() when the memory is no longer needed.

✅ An example of bad practice (without free()):

int **matrix = (int **)malloc(3 * sizeof(int *));
for (int i = 0; i < 3; i++) {
    matrix[i] = (int *)malloc(3 * sizeof(int));
}

// free(matrix) is missing here → memory leak!

✅ The correct way:

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

free(matrix); // Freeing the main pointer

🔴 Dereferencing an unallocated pointer

  • Problem: If we use a pointer that we have not initialized (a NULL pointer), the program may crash.
  • Solution: Always check whether malloc succeeded.

✅ An example of good practice:

int *arr = (int *)malloc(10 * sizeof(int));
if (arr == NULL) {
    printf("Allocation failed!\n");
    return 1;
}

Conclusion

Dynamic allocation gives more flexibility and better control over memory, but it requires careful management to avoid mistakes such as memory leaks. Static allocation is safer, but limited in size and flexibility.

📌 Best practice:

✅ Use dynamic allocation when the size of the data is not known in advance.

✅ Always free memory with free().

✅ Check whether the allocation succeeded (if (ptr == NULL)).

Two-dimensional dynamic arrays in C

In C, looking at the matrix example on the page Two-dimensional arrays – matrices in C++, a row of integers can be defined like this:

int *r = (int *)malloc(n * sizeof(int));

The function malloc(), which is in the standard header <stdlib.h>, allocates memory of size n*4 bytes in this case, because the operator sizeof(int) gives the size of an int in bytes, and here that is 4, because that is how much memory int data takes in C.

To create a matrix of size m*n we introduce a pointer to a pointer:

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

Since the matrix is created as an array of pointers, where those pointers point to the individual rows of the matrix, the operator sizeof here refers to pointers to integer data, hence sizeof(int*). Creating and reading the whole matrix would be:

int **A;
int m = 4, n = 3;                          // m rows, n columns
A = (int **)malloc(m * sizeof(int *));
printf("Matrix?\n");

for (int i = 0; i < m; i++) {
    A[i] = (int *)malloc(n * sizeof(int));
    for (int j = 0; j < n; j++) {
        scanf("%d", &A[i][j]);
    }
}

First the memory of the pointer "A" to the pointers that will point to the rows of the matrix is allocated dynamically. The rows are created inside the for loop as A[i]. That is a pointer to the current row "i". The memory for the data in row A[i] must also be allocated dynamically, by calling the function malloc().

Other functions for dynamic memory allocation from the header <stdlib.h>

Besides the function malloc(), which reserves memory, there are also the functions:

realloc() – changes the size of memory previously reserved with the function malloc()

free(A) – frees the memory pointed to by the pointer A

Printing the matrix that was created and read would be:

Printing matrices in C

printf("Printing the matrix:\n");

for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        printf("%3d", A[i][j]);
    }
    printf("\n");
}

After running the program and entering the data 1 2 3 4 5 6 7 8 9 10 11 12, the console shows:

Matrix?
1 2 3
4 5 6
7 8 9
10 11 12
Printing the matrix:
  1  2  3
  4  5  6
  7  8  9
 10 11 12

Copying a matrix in C

To copy the elements of a dynamic matrix, we will make a separate function for it and pass the pointer to the matrix as a parameter, together with the dimensions m and n. Passing the pointer to the matrix ensures that any change made to the matrix inside the function is reflected in the original. Copying is actually writing the data into a new matrix, which is then returned from the function. The function is shown below:

int **copyMatrix(int **aT, int m, int n) {
    int **aC;
    // Allocate memory for the new matrix aC
    aC = (int **)malloc(m * sizeof(int *));
    for (int i = 0; i < m; i++) {
        // Allocate memory for the columns of row i of matrix aC
        aC[i] = (int *)malloc(n * sizeof(int));
        for (int j = 0; j < n; j++) {
            // Copy the data from the original matrix aT into the new matrix aC
            aC[i][j] = aT[i][j];
        }
    }
    return aC;
}

Since the matrix is printed several times, we will create a function for printing, which takes as parameters a pointer to a pointer, i.e. a pointer to the matrix A, and the dimensions of the matrix m and n. The function is shown below:

void printMatrix(int **a, int m, int n) {
    // Go through all rows of the matrix
    for (int i = 0; i < m; i++) {
        // Go through all columns of the matrix in the current row
        for (int j = 0; j < n; j++) {
            // Print the element at position [i][j] with a space between the numbers
            printf("%d ", a[i][j]);
        }
        // After printing one row, go to a new line
        printf("\n");
    }
}

The code in the main function that creates a new matrix, calls the copying function and then the printing function looks like this:

int **b;
// Make a copy of matrix A with dimensions m x n
b = copyMatrix(A, m, n);

// Print the copied matrix using the function printMatrix
printf("Copied matrix:\n");
printMatrix(b, m, n);

If we now run the application (with the same input as above), it shows:

Copied matrix:
1 2 3
4 5 6
7 8 9
10 11 12 

The code can also be changed at the beginning so that the user enters the number of rows and columns.

The transposed matrix

We get the transposed matrix when we swap the rows and columns of the starting matrix. The transposed matrix is determined as part of determining the inverse matrix.

Transposed matrix  A^T
Inverse matrix     A^-1

We can determine the transposed (square, n*n) matrix in a separate function, as shown below:

void transpose(int **a, int n) {
    // Go through the rows of the matrix
    for (int i = 0; i < n; i++) {
        // Go through the elements above the main diagonal
        for (int j = i; j < n; j++) {
            // Swap the elements to transpose
            int b = a[i][j];
            a[i][j] = a[j][i];
            a[j][i] = b;
        }
    }
}

In the inner, i.e. nested, for loop the element in row i and column j is swapped with the element in row j and column i. The inner loop does not start with j=0 but with j=i, because in the columns with j<i the swap has already been done.

The function transpose() is called in the main() function:

#include <stdio.h>

int main() {
    /* Assumption: the matrix A (n x n) and n are initialized above this part of the code */
    // Call the function that transposes the matrix
    transpose(A, n);
    // Print that the matrix has been transposed
    printf("Transposed matrix:\n");
    // Print the elements of the transposed matrix
    printMatrix(A, n, n);
}

For the 3*3 matrix 1 2 3 / 4 5 6 / 7 8 9 this prints:

Transposed matrix:
1 4 7
2 5 8
3 6 9 

Computing the determinant of a square matrix

Let us look at the following example: Read n, and then read the elements of a matrix of size n*n. Make a function that computes the determinant of the matrix A of order n*n, then compute the determinant of the matrix that was read and show the result on the screen.
Example:
Input

3
3 5 6
2 -6 3
0 1 7
Output
-193
The task is explained in detail on the web page:

Recursive algorithms

Detailed code examples

In this part we show how two-dimensional dynamic arrays (matrices) are allocated, initialized, used and freed in C.

1. Dynamic allocation of a matrix

In C, two-dimensional arrays are allocated with a pointer to a pointer and the function malloc.

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

int main() {
    int rows = 3, cols = 4; // Dimensions of the matrix
    int **matrix; // A pointer to an array of pointers (the rows of the matrix)

    // 1. Allocate memory for the array of row pointers
    matrix = (int **)malloc(rows * sizeof(int *));

    // 2. Allocate memory for every row
    for (int i = 0; i < rows; i++) {
        matrix[i] = (int *)malloc(cols * sizeof(int));
    }

    // 3. Initialize the matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            // Example values
            matrix[i][j] = i * cols + j;
        }
    }

    // 4. Print the matrix
    printf("Matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    // 5. Free the memory
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
    return 0;
}

The program prints:

Matrix:
0 1 2 3
4 5 6 7
8 9 10 11 

Explanation of the code:

  • We use malloc to allocate memory.
  • We allocate memory for an array of pointers (int **matrix).
  • Every pointer points to an array of int elements, which forms a two-dimensional array.
  • We free the memory in reverse order – first the individual rows, then the main array of pointers.

2. Alternative allocation (one pointer)

It is possible to allocate a two-dimensional array as one array, which reduces the number of allocations and calls to malloc:

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

int main() {
    int rows = 3, cols = 4;
    int *matrix; // one contiguous block of rows * cols elements

    // 1. Allocate all the memory at once
    matrix = (int *)malloc(rows * cols * sizeof(int));

    // 2. Initialize the matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            // Example values
            matrix[i * cols + j] = i * cols + j;
        }
    }

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

    // 4. Free the memory
    free(matrix);
    return 0;
}

The output is the same as in the previous example.

Advantages of this approach:

✅ Fewer calls to malloc, which improves performance.

✅ Simpler freeing of memory (free(matrix), instead of a loop with free(matrix[i])).

✅ More efficient use of the processor's cache memory.

Conclusion

There are two ways to allocate dynamic matrices in C:

  1. The classic way (a pointer to a pointer) – More flexible, but it requires more malloc calls and more complex freeing of memory.
  2. One array with pointer arithmetic – A more efficient approach with simpler freeing of memory.

Connection with related topics

For a better understanding of dynamic memory allocation, we recommend the following related articles:

Understanding these topics will help you better understand how dynamic allocation works and how to avoid the most common mistakes.

Check your knowledge

Open the quiz

Quiz: Dynamic arrays in C

1. What does malloc(n * sizeof(int)) return?




2. What must be done when memory is no longer needed?




3. For a matrix int **m created with malloc for every row, what is freed?




4. Why do we check whether malloc returned NULL?