Array in C is static in nature, so its size should be known at compile time and we can’t change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn’t have enough space left for required elements or we allotted more than the required memory leading to memory wastage. To solve this problem, dynamic arrays come into the picture.
A Dynamic Array is allocated memory at runtime and its size can be changed later in the program.
We can create a dynamic array in C by using the following methods:
- Using malloc() Function
- Using calloc() Function
- Resizing Array Using realloc() Function
- Using Variable Length Arrays(VLAs)
- Using Flexible Array Members
1. Dynamic Array Using malloc() Function
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It is defined inside <stdlib.h> header file.
Syntax:
ptr = (cast-type*) malloc(byte-size);
We can use this function to create a dynamic array of any type by simply allocating a memory block of some size and then typecasting the returned void pointer to the pointer of the required type.
Example:
ptr = (int*) malloc(100 * sizeof(int));
In the above example, we have created a dynamic array of type int and size 100 elements.
Note: It is to be noted that if malloc fails to allocate the required memory, it returns the NULL pointer. So, it is a good practice to check for NULL pointer to see if the memory is successfully allocated or not.
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int size;
printf ( "Enter size of elements:" );
scanf ( "%d" , &size);
ptr = ( int *) malloc (size * sizeof ( int ));
if (ptr == NULL) {
printf ( "Memory not allocated.\n" );
}
else {
printf ( "Memory successfully allocated using "
"malloc.\n" );
for ( int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}
printf ( "The elements of the array are: " );
for ( int k = 0; k < size; ++k) {
printf ( "%d, " , ptr[k]);
}
}
return 0;
}
|
Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
2. Dynamic Array Using calloc() Function
The “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type and initialized each block with a default value of 0.
The process of creating a dynamic array using calloc() is similar to the malloc() method. The difference is that calloc() takes arguments instead of one as compared to malloc(). Here, we provide the size of each element and the number of elements required in the dynamic array. Also, each element in the array is initialized to zero.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
Example:
ptr = (int*) calloc(5, sizeof(float));
In the above example, we have created a dynamic array of type float having five elements.
Let’s take another example to create a dynamic array using the calloc() method.
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int size;
printf ( "Enter size of elements:" );
scanf ( "%d" , &size);
ptr = ( int *) calloc (size, sizeof ( int ));
if (ptr == NULL) {
printf ( "Memory not allocated.\n" );
}
else {
printf ( "Memory successfully allocated using "
"malloc.\n" );
for ( int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}
printf ( "The elements of the array are: " );
for ( int k = 0; k < size; ++k) {
printf ( "%d, " , ptr[k]);
}
}
return 0;
}
|
Output:
Enter size of elements:6
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6,
3. Dynamically Resizing Array Using realloc() Function
The “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.
Using this function we can create a new array or change the size of an already existing array.
Syntax:
ptr = realloc(ptr, newSize);
Let’s take an example to understand this properly.
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int size = 5;
ptr = ( int *) calloc (size, sizeof ( int ));
if (ptr == NULL) {
printf ( "Memory not allocated.\n" );
exit (0);
}
else {
printf ( "Memory successfully allocated using "
"calloc.\n" );
}
for ( int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}
printf ( "The elements of the array are: " );
for ( int k = 0; k < size; ++k) {
printf ( "%d, " , ptr[k]);
}
printf ( "\n" );
size = 10;
int *temp = ptr;
ptr = realloc (ptr, size * sizeof ( int ));
if (!ptr) {
printf ( "Memory Re-allocation failed." );
ptr = temp;
}
else {
printf ( "Memory successfully re-allocated using "
"realloc.\n" );
}
for ( int j = 5; j < size; ++j) {
ptr[j] = j + 10;
}
printf ( "The new elements of the array are: " );
for ( int k = 0; k < size; ++k) {
printf ( "%d, " , ptr[k]);
}
return 0;
}
|
Output
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Memory successfully re-allocated using realloc.
The new elements of the array are: 1, 2, 3, 4, 5, 15, 16, 17, 18, 19,
To Know more about these above methods, please refer to the article – malloc, calloc,free in C
4. Variable Length Arrays(VLAs)
Variable length arrays or VLAs, are those arrays in which we can determine the size of the array at the run time. It allocates the memory in the stack and it’s based on the local scope level.
The size of a variable length array cannot be changed once it is defined and using variable length array as its found down sides as compared to above methods.
Example:
C
#include <stdio.h>
int main()
{
int n;
printf ( "Enter the size of the array: " );
scanf ( "%d" , &n);
int arr[n];
printf ( "Enter elements: " );
for ( int i = 0; i < n; ++i) {
scanf ( "%d" , &arr[i]);
}
printf ( "Elements of VLA of Given Size: " );
for ( int i = 0; i < n; ++i) {
printf ( "%d " , arr[i]);
}
return 0;
}
|
Output:
Enter the size of the array: 5
Enter elements: 1 2 3 4 5
Elements of VLA of Given Size: 1 2 3 4 5
To know more about variable length arrays, please refer to the article –Variable Length Arrays in C/C++.
5. Flexible Array Members
The flexible array members are the array that is defined inside a structure without any dimension and their size is flexible. This feature was introduced in C99 standard.
We can control the size of a flexible member using malloc() function.
There are a few rules to follow in the case of flexible array members:
- The array inside the structure should preferably be declared as the last member of the structure and its size is variable(can be changed at runtime).
- The structure must contain at least one more named member in addition to the flexible array member.
Let’s take the following structure for example
struct student
{
int len;
int
};
Now to allocate memory, we will use malloc() function as shown below.
struct student *s = malloc(sizeof(*s) + 5 * sizeof(int));
Example:
C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int len;
int arr[];
} fam;
int main()
{
fam* fam1
= (fam*) malloc ( sizeof (fam*) + 5 * sizeof ( int ));
fam* fam2
= (fam*) malloc ( sizeof (fam*) + 10 * sizeof ( int ));
for ( int i = 0; i < 5; i++) {
fam1->arr[i] = i + 1;
}
for ( int i = 0; i < 10; i++) {
fam2->arr[i] = i + 10;
}
printf ( "Array of Size 5:\n" );
for ( int i = 0; i < 5; i++) {
printf ( "%d, " , fam1->arr[i]);
}
printf ( "\n" );
printf ( "Array of size 10:\n" );
for ( int i = 0; i < 10; i++) {
printf ( "%d, " , fam2->arr[i]);
}
return 0;
}
|
Output
Array of Size 5:
1, 2, 3, 4, 5,
Array of size 10:
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
To know more about flexible array members, please refer to the article – Flexible Array Members Structure in C.
Dynamic Allocation of Two-Dimensional Array
We can also create a two-dimensional dynamic array in c. These are the following different ways to create a 2D dynamic array.
- Using a single pointer and a 1D array with pointer arithmetic
- Using an array of pointers
- Using a pointer to a pointer
- Using a double-pointer and one malloc call
- Using a pointer to Variable Length Array
- Using a pointer to the first row of VLA
To know more about the Dynamic Allocation of Two-Dimensional Arrays, refer to the article – How to dynamically allocate a 2D array in C?