How to dynamically allocate a 2D array in C?

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.


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

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.


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

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.


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

4) Using double pointer and one malloc call


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

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].


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

6) Using a pointer to the first row of VLA

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


Output
1 2 3 4 5 6 7 8 9 10 11 12
Abhay Rathi Like Article -->

Please Login to comment.

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 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 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 How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?

In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su

6 min read What’s difference between “array” and “&array” for “int array[5]” ?

If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min

4 min read array::front() and array::back() in C++ STL

Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::front() This function is used to reference the first element of the array container. This function can be used to fetch the first element of an array. Synt

3 min read array::fill() and array::swap() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::fill() This function is used to set a common value for all the elements of the array container. Syntax : arrayname.fill(value) Parameters : The value to be

3 min read array::begin() and array::end() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::begin() begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterat

3 min read array::cbegin() and array::cend() in C++ STL

array::cbegin() is a built-in function in C++ STL which returns a const_iterator pointing to the first element in the array. It cannot be used to modify the element in the array which is possible using array::begin(). Syntax: array_name.cbegin() Parameters: The function does not accept any parameters. Return Value: The function returns a const_iter

2 min read array::rbegin() and array::rend() in C++ STL

array::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax:array_name.rbegin()Parameters: The function does not accept any parameter. Return value: The function returns a reverse iterator pointing to the last element in the container. Program to demonstrate the array::rbe

2 min read Difference between pointer to an array and array of pointers

Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = <3, 4, 5 >; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the

4 min read Jagged Array or Array of Arrays in C with Examples

Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = < <0, 1, 2>, , , >; Below are the methods to implement the j

3 min read Array of Structures vs Array within a Structure in C

Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element

5 min read Array of Structures vs Array within a Structure in C++

In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a

4 min read Pointer to an Array | Array Pointer

Prerequisite: Pointers Introduction Consider the following program: [GFGTABS] C #include<stdio.h> int main() < int arr[5] = < 1, 2, 3, 4, 5 >; int *ptr = arr; printf("%p\n", ptr); return 0; > [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer

9 min read Pointer vs Array in C

Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0

1 min read How to Return a Local Array From a C++ Function?

Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include <i

3 min read Properties of Array in C

An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve different problems not only in C but also in other langua

8 min read Program to reverse an array using pointers

Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .

4 min read Sum of array using pointer arithmetic

Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi

2 min read array::operator[ ] in C++ STL

Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only diffe

2 min read array::size() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::size() size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname.size() Parameter

1 min read array::empty() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::empty() empty() function is used to check if the array container is empty or not. Syntax : arrayname.empty() Parameters : No parameters are passed. Returns

1 min read array::at() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::at() This function is used to return the reference to the element present at the position given as the parameter to the function. Syntax: array_name.at(posi

2 min read Sort an array using socket programming in C

Given an array of unsorted positive integer, sort the given array using the Socket programming . Examples: Input : 4 5 6 1 8 2 7 9 3 0 Output :0 1 2 3 4 5 6 7 8 9 Input : 9 8 1 4 0 Output : 0 1 4 8 9 Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server). Run the program using ./server and ./client (Please note :

3 min read array::max_size() in C++ STL

Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::max_size() This function returns the maximum number of elements that the array container can contain. In case of an array, size() and max_size() function al

1 min read STD::array in C++

The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the array header: #include <array> Let's see an ex

5 min read 4 Dimensional Array in C/C++

Prerequisite :Array in C/C++, More on array A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array. More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays. Declaration of a Multidimensional Array in C: Syntax: data_