Skip to content
StudyFame

Dynamic Arrays in C

A normal 2D array like int m[10][10] has fixed rows and columns. But what if the user decides the matrix size at run time? Or each row needs a different length, like Pascal's triangle?

In this lesson you will build dynamic arrays: a 1D array sized at run time, two ways to make a dynamic 2D array, and a jagged array with rows of different lengths. You will also learn the right order to free them.

What You Will Learn

  • What a dynamic array is.
  • How to create a 1D dynamic array.
  • Method 1: a 2D array as an array of row pointers (int **).
  • Method 2: a 2D array as one block with index arithmetic.
  • How to make a jagged array.
  • How to free a dynamic 2D array correctly.

What is a Dynamic Array in C?

Exam definition: A dynamic array is an array whose memory is allocated at run time on the heap (using malloc/calloc), so its size can be chosen while the program runs and changed later with realloc. It is accessed through a pointer and must be released with free.

Memory trick: A dynamic 2D array (Method 1) is like a train booking chart: first you get a list of coach numbers (row pointers), then each coach gets its own seats (a row). Taking the train apart: remove the seats first, then the coach list.

Syntax: 1D and 2D Dynamic Arrays

/* 1D */
int *a = malloc(n * sizeof *a);              /* a[i] */

/* 2D, Method 1: array of row pointers */
int **m = malloc(rows * sizeof *m);          /* list of row pointers */
for (i = 0; i < rows; i++)
    m[i] = malloc(cols * sizeof *m[i]);      /* each row */
/* use m[i][j]; free each m[i], then m */

/* 2D, Method 2: one block */
int *block = malloc(rows * cols * sizeof *block);
/* element (i, j) is block[i * cols + j]; one free(block) */
Method 1 (int **m), rows = 3, cols = 4

 m --> +------+       +----+----+----+----+
       | m[0] | ----> |    |    |    |    |   row 0 (separate block)
       +------+       +----+----+----+----+
       | m[1] | ----> |    |    |    |    |   row 1
       +------+       +----+----+----+----+
       | m[2] | ----> |    |    |    |    |   row 2
       +------+       +----+----+----+----+

Method 2 (one block): [ row 0 | row 1 | row 2 ]  index = i * cols + j
PointMethod 1: int **Method 2: one block
Accessm[i][j] (natural)b[i * cols + j]
Allocationsrows + 1 mallocs1 malloc
FreeEach row, then the pointer arrayOne free
Rows of different length?Yes (jagged)No
Memory contiguous?No (rows may be scattered)Yes (faster, cache-friendly)

Example 1: Matrix of User-Chosen Size (Method 1)

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

int main(void)
{
    int rows, cols, i, j;
    int **m;

    printf("Rows and columns: ");
    scanf("%d %d", &rows, &cols);

    m = malloc(rows * sizeof *m);                /* row pointers */
    if (m == NULL)
        return 1;
    for (i = 0; i < rows; i++)
    {
        m[i] = malloc(cols * sizeof *m[i]);      /* one row */
        if (m[i] == NULL)
        {
            while (--i >= 0)                     /* undo rows made so far */
                free(m[i]);
            free(m);
            return 1;
        }
    }

    for (i = 0; i < rows; i++)                   /* fill: m[i][j] = i*cols+j+1 */
        for (j = 0; j < cols; j++)
            m[i][j] = i * cols + j + 1;

    printf("Matrix %d x %d:\n", rows, cols);
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
            printf("%4d", m[i][j]);
        printf("\n");
    }

    for (i = 0; i < rows; i++)                   /* free rows first */
        free(m[i]);
    free(m);                                     /* then the pointer array */
    m = NULL;
    return 0;
}

Output

Rows and columns: 2 3
Matrix 2 x 3:
   1   2   3
   4   5   6

Code Explanation

  1. int **m is a pointer to the first of several row pointers (a double pointer).
  2. malloc(rows * sizeof *m) allocates the list of row pointers; sizeof *m is the size of an int *.
  3. The loop gives each row its own block of cols ints. If one fails, we free the rows already made, then the list: no leak.
  4. m[i][j] works naturally: m[i] is row i's pointer, [j] picks the column.
  5. Freeing goes in reverse order of creation: rows first, then m. Freeing m first would lose the row pointers and leak every row.

How a Jagged Array Works

With Method 1, each row is a separate malloc, so rows can have different lengths. Pascal's triangle is a perfect example: row i has i + 1 numbers.

row 0:  1
row 1:  1 1
row 2:  1 2 1
row 3:  1 3 3 1           each inner number = sum of the two above
row 4:  1 4 6 4 1         row i has (i + 1) elements

Example 2: Pascal's Triangle (Jagged) and a One-Block Matrix

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

int main(void)
{
    int n = 5, i, j, rows = 3, cols = 4;
    int **tri = malloc(n * sizeof *tri);
    int *block = malloc(rows * cols * sizeof *block);

    if (tri == NULL || block == NULL)
        return 1;

    /* jagged: row i has i + 1 elements */
    for (i = 0; i < n; i++)
    {
        tri[i] = malloc((i + 1) * sizeof *tri[i]);
        if (tri[i] == NULL)
            return 1;
        tri[i][0] = tri[i][i] = 1;
        for (j = 1; j < i; j++)
            tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j];
    }

    printf("Pascal's triangle:\n");
    for (i = 0; i < n; i++)
    {
        printf("%*s", (n - i - 1) * 2, "");      /* indent */
        for (j = 0; j <= i; j++)
            printf("%4d", tri[i][j]);
        printf("\n");
    }

    /* one block: element (i, j) at block[i * cols + j] */
    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++)
            block[i * cols + j] = (i + 1) * (j + 1);

    printf("Multiplication grid (one block):\n");
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
            printf("%4d", block[i * cols + j]);
        printf("\n");
    }

    for (i = 0; i < n; i++)
        free(tri[i]);
    free(tri);
    free(block);                                 /* one free for one block */
    return 0;
}

Output

Pascal's triangle:
           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1
Multiplication grid (one block):
   1   2   3   4
   2   4   6   8
   3   6   9  12
  • The triangle allocates exactly 1 + 2 + 3 + 4 + 5 = 15 ints. A fixed 5 × 5 array would waste 10.
  • printf("%*s", width, "") prints width spaces, which centres the triangle.
  • The one-block grid uses a single malloc and a single free, and keeps all data together in memory.

Important Points to Remember

  • A dynamic array is allocated at run time and accessed through a pointer.
  • 1D: malloc(n * sizeof *a).
  • 2D Method 1: int ** + one malloc per row; supports jagged rows.
  • 2D Method 2: one block, index i * cols + j; one free.
  • Free Method 1 in reverse: rows first, then the row-pointer array.
  • If a row allocation fails, free what was already allocated.

Common Mistakes Beginners Make

MistakeWhat happensFix
free(m) before freeing rowsAll rows leakFree m[i] first
malloc(rows * sizeof(int)) for the pointer arrayToo small on 64-bit (int 4, pointer 8)rows * sizeof *m (or sizeof(int *))
Passing int m[3][4] to an int ** parameterWrong type: crashUse int (*m)[4] for static 2D arrays
Wrong formula block[j * cols + i]Wrong elements, overflowblock[i * cols + j]
Not freeing on a mid-way failurePartial leakUndo previous rows

Dynamic Arrays Practice Questions

  1. What is a dynamic array?
  2. Write code to allocate a dynamic 2D array of 4 rows and 5 columns using int **.
  3. In what order must that array be freed? Why?
  4. What is a jagged array? Which method supports it?
  5. In a one-block 2D array with 6 columns, where is element (2, 3)?
Show answers
  1. An array allocated on the heap at run time, so its size can be chosen (and changed) while the program runs.
  2. int **m = malloc(4 * sizeof *m); for (i = 0; i < 4; i++) m[i] = malloc(5 * sizeof *m[i]);
  3. Each row first, then m. Freeing m first loses the row pointers, leaking the rows.
  4. A 2D array whose rows have different lengths. The row-pointer (int **) method.
  5. Index 2 × 6 + 3 = 15.

Coding Exercise

Allocate a dynamic 1D array of n = 5 ints, fill it with 2, 4, 6, 8, 10, then use realloc to extend it to 8 elements filled with 12, 14, 16. Print all elements and free the memory.

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

int main(void)
{
    int n = 5, i;
    int *a = malloc(n * sizeof *a);
    int *tmp;

    if (a == NULL)
        return 1;
    for (i = 0; i < n; i++)
        a[i] = 2 * (i + 1);

    tmp = realloc(a, 8 * sizeof *a);
    if (tmp == NULL) { free(a); return 1; }
    a = tmp;
    for (i = n; i < 8; i++)
        a[i] = 2 * (i + 1);
    n = 8;

    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    free(a);
    return 0;
}
2 4 6 8 10 12 14 16

Quick Quiz: Dynamic Arrays (MCQ)

  1. For a dynamic 2D array of rows × cols using int **m, how many malloc calls are needed?

    A) 1   B) rows   C) rows + 1   D) rows × cols

  2. The pointer array in Method 1 is allocated with:

    A) malloc(rows * sizeof(int))   B) malloc(rows * sizeof(int *))   C) malloc(cols)   D) malloc(1)

  3. Element (i, j) in a single-block 2D array of cols columns is:

    A) b[i + j]   B) b[i * cols + j]   C) b[j * rows + i]   D) b[i][j]

  4. A 2D array with rows of different lengths is called:

    A) Sparse   B) Jagged   C) Static   D) Square

  5. Correct way to free an int **m 2D array:

    A) free(m); only   B) Free each m[i], then m   C) Free m, then each m[i]   D) No free needed

Show answers
  1. C: rows + 1.
  2. B: rows * sizeof(int *).
  3. B: b[i * cols + j].
  4. B: jagged.
  5. B: rows first, then m.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Dynamic arrayHeap array sized at run time
1Dmalloc(n * sizeof *a)
2D Method 1int **, rows + 1 mallocs, m[i][j]
2D Method 2One block, b[i * cols + j]
Jagged arrayRows of different lengths (Method 1)
Free orderRows first, then the pointer array

Frequently asked questions

How do you create a dynamic 2D array in C?
Allocate an array of row pointers, then malloc each row; or allocate one block of rows × cols and index with i * cols + j.
How do you free a dynamic 2D array?
Free every row first, then free the row-pointer array.
What is a jagged array?
A 2D array where each row can have a different number of columns, built with separate row allocations.

Remember

  • Method 1 = train chart: coach list, then seats per coach.
  • Dismantle in reverse: seats first, then the list.

Next Topic

Next lesson: File Handling in C. You will start Module 13 and learn to save data permanently in files.