The Wayback Machine - https://web.archive.org/web/20240607003758/https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/
Open In App

How to dynamically allocate a 2D array in C?

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
 

Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).
In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we created a 2D array with r = 3, c = 4 and the following values 

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

1) Using a single pointer and a 1D array with pointer arithmetic: 
A simple way is to allocate a memory block of size r*c and access its elements using simple pointer arithmetic. 
 

C




#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int r = 3, c = 4;
 
    int* ptr = malloc((r * c) * sizeof(int));
 
    /* Putting 1 to 12 in the 1D array in a sequence */
    for (int i = 0; i < r * c; i++)
        ptr[i] = i + 1;
 
    /* Accessing the array values as if it was a 2D array */
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++)
            printf("%d ", ptr[i * c + j]);
        printf("\n");
    }
 
    free(ptr);
 
    return 0;
}


Output

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

Time Complexity : O(R*C),  where R and C is size of row and column respectively.
Auxiliary Space: O(R*C), where R and C is size of row and column respectively.
 
2) Using an array of pointers 
We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
 

C




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4, i, j, count;
 
    int* arr[r];
    for (i = 0; i < r; i++)
        arr[i] = (int*)malloc(c * sizeof(int));
 
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count
 
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            printf("%d ", arr[i][j]);
 
    /* Code for further processing and free the
      dynamically allocated memory */
 
    for (int i = 0; i < r; i++)
        free(arr[i]);
 
    return 0;
}


Output

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

Time Complexity: O(R*C) 

Here R and C is size of row and column respectively.

Auxiliary Space: O(R*C)

The extra space is used to store the elements of the matrix.

3) Using pointer to a pointer 
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2. 
 

C




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4, i, j, count;
 
    int** arr = (int**)malloc(r * sizeof(int*));
    for (i = 0; i < r; i++)
        arr[i] = (int*)malloc(c * sizeof(int));
 
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
 
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            printf("%d ", arr[i][j]);
 
    /* Code for further processing and free the
       dynamically allocated memory */
 
    for (int i = 0; i < r; i++)
        free(arr[i]);
 
    free(arr);
 
    return 0;
}


Output

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

Time Complexity: O(R*C)

Here R and C is size of row and column respectively.

Auxiliary Space: O(R*C)

The extra space is used to store the elements of the matrix.
4) Using double pointer and one malloc call 
 

C




#include<stdio.h>
#include<stdlib.h>
 
int main()
{
    int r=3, c=4, len=0;
    int *ptr, **arr;
    int count = 0,i,j;
 
    len = sizeof(int *) * r + sizeof(int) * c * r;
    arr = (int **)malloc(len);
 
    // ptr is now pointing to the first element in of 2D array
    ptr = (int *)(arr + r);
 
    // for loop to point rows pointer to appropriate location in 2D array
    for(i = 0; i < r; i++)
        arr[i] = (ptr + c * i);
 
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
 
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            printf("%d ", arr[i][j]);
 
    return 0;
}


Output

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

Time Complexity: O(R*C)

Here R and C is size of row and column respectively.

Auxiliary Space: O(R*C)

The extra space is used to store the elements of the matrix.
Thanks to Trishansh Bhardwaj for suggesting this 4th method.

5) Using a pointer to Variable Length Array.

The dimensions of VLA are bound to the type of the variable. Therefore one form a pointer to an array with run-time defined shape.
The pointer has to be dereferenced before subscripting with syntax (*arr)[i][j].
 

C




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int row = 3, col = 4, i, j, count;
 
    int (*arr)[row][col] = malloc(sizeof *arr);
     
    count = 0;
    for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
            (*arr)[i][j] = ++count;
 
    for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
            printf("%d ", (*arr)[i][j]);
 
    free(arr);
     
    return 0;
}


Output

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

Time Complexity: O(R*C)

Here R and C is size of row and column respectively.

Auxiliary Space: O(R*C)

The extra space is used to store the elements of the matrix.

6) Using a pointer to the first row of VLA

Similar to 5 but allows arr[i][j] syntax.

C




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int row = 3, col = 4, i, j, count;
 
    int (*arr)[col] = calloc(row, sizeof *arr);
     
    count = 0;
    for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
            arr[i][j] = ++count;
 
    for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
            printf("%d ", arr[i][j]);
 
    free(arr);
     
    return 0;
}


Output

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

Time Complexity: O(R*C)

Here R and C is size of row and column respectively.

Auxiliary Space: O(R*C)

The extra space is used to store the elements of the matrix.



Previous Article
Next Article

Similar Reads

How to dynamically allocate a 3D array in C++
Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to
4 min read
How to Dynamically Allocate Memory for an Array of Strings?
Dynamic memory and static memory are two types of memory allocation methods in C++ programming. Dynamic memory allows programmers to allocate memory to data structures at runtime. Dynamic memory can also be freed after work is done which also makes it more efficient. In this article, we will learn how to allocate an array of strings in dynamic memo
2 min read
How to Dynamically Allocate an Array in C++?
In C++, dynamic memory allocation allows us to allocate memory during runtime. Dynamic allocation in an array is particularly useful when the size of an array is not known at compile time and needs to be specified during runtime. In this article, we will learn how to dynamically allocate an array in C++. Dynamic Allocation of Arrays in C++In C++, w
2 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
How to declare a 2D array dynamically in C++ using new operator
Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]….[sizeN]; data_type: Type of data to b
4 min read
Dynamically Growing Array in C
Prerequisite: Dynamic Memory Allocation in C A Dynamically Growing Array is a type of dynamic array, which can automatically grow in size to store data. The C language only has static arrays whose size should be known at compile time and cannot be changed after declaration. This leads to problems like running out of space or not using the allocated
7 min read
How to Dynamically Create Array of Structs in C?
In C, an array is a data structure that stores the collection of elements of similar types. Structs in C allow the users to create user-defined data types that can contain different types of data items. In this article, we will learn how we can create an array of structs dynamically in C. Dynamically Create Array of Structs in C To dynamically crea
2 min read
How to Find the Size of a Dynamically Allocated Array in C++?
In C++, dynamic memory allocation enables the users to manage the memory resources during the execution of the program and is very useful for arrays when the size of the array is not known at compile time or during any other times for flexibility. In this article, we will learn how to find the size of a dynamically allocated array in C++. Finding t
2 min read
How to Dynamically Resize a C++ Array?
In C++, an array is a collection of elements of the same type placed in contiguous memory locations. In this article, we will learn how to dynamically resize an array in C++. Example: Input: myArray = {10, 20, 30, 40, 50};Output:Resized array: 10 20 30 40 50 0 0 0 0 0 Resizing a Dynamic Array in C++ In C++, the size of an array is static, but we ca
3 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read