How to dynamically allocate a 1D and 2D array in c.

In C language, we can create both statically and dynamically allocated array.These arrays can be one dimensional or multiple dimensional. In statically allocated array problem is that we have to specify the size of the array before the compilation. So the problem is generated when we don’t know how much size of the array required ahead of time.

We can resolve this issues using the dynamic memory allocation.The advantage of a dynamically allocated array is that it is allocated on the heap at runtime. The C language provides library function to request for the heap memory at runtime.



In below program, I am using malloc to allocate the dynamic memory for the 1D and 2D array.

Syntax of malloc

void * malloc (size_t size)

Parameters

size ==> This is the size of the memory block, in bytes.

Return Value

Returns a pointer to the allocated memory, if enough memory is not available then it returns NULL.

1D array using the dynamic memory allocation

In below example, I am creating a pointer to an integer and assign it heap memory. When memory is successfully assigned to the pointer then we can use this pointer as a 1D array and using the square braces “[]” we can access the pointer as like the statically allocated array.

See the below image for the better understanding.

dynamic allocation of array in c

Let’s see a program example,





2D array using the dynamic memory allocation

In C language like the 1D array, we can also create the 2D array using the dynamic memory allocation at runtime. In below, I am listing some generic steps to create the 2D array using the pointers.

Steps to creating 2D array using pointer to pointer

  • Create a pointer to pointer and allocate the memory for the row using malloc().

  • Allocate memory for each row columns using the malloc().

  • If each row does not have a same number of columns then allocate memory for each row individually.

Let’s see the below picture where I am creating a 5×5  2D array using the dynamic memory allocation.

dynamic array in c using malloc

Method 1:

In which one malloc for array of row and “N” (number of columns) mallocs for each row.

Note: Every location in each row is a contiguous memory but it is not necessary every row at contiguous memory in heap.





Method 2:

Using this method we can save memory. In which we can only do a single malloc and create a large 1D array. Here we will map 2D array on this created 1D array.

Method 3

We can also create a non-square two-dimensional array in c using the dynamic memory allocation. Here need to do explicitly malloc for each rows column.

Consider the below image and example for better understanding.

2d array in c using pointers

 





Leave a Reply