In c language we can create both statically and dynamically allocated array.These array 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 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 dynamically allocated array is that it is allocated on the heap at run time. The C language provide library function to request for the heap memory at run time.



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 return NULL.

1D array using the dynamic memory allocation

In below example, I am creating a pointer to integer and assign it heap memory. When memory is successfully assigned to the pointer than we can use this pointer as 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 run time. 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 the each row columns using the malloc().

  • If each rows does not have 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 column) mallocs for each row .

Note: Every location in each rows  are contiguous memory but it is not necessary every rows 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 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