Introduction
We'll learn how to use standard library functions like malloc() and calloc() to create a dynamic Array in c in this blog.
An array is a collection of a fixed number of values. You can't change the size of an array once it's been declared.
It's possible that the size of the Array you declared is insufficient at times. You can manually set RAM during runtime to remedy this problem. In C programming, we called it dynamic memory allocation. Malloc(), calloc(), and realloc() are library functions that are used to allocate memory dynamically.
The header file <stdlib.h> defines these functions.
Also see: C Static Function and Short int in C Programming
Dynamic Memory Allocation
C Dynamic Memory Allocation is a process for changing the size of a Data Structure (such as an Array) during runtime.
-
C malloc() method
-
C calloc() method
-
C free() method
-
C realloc() method
-
Using Variable Length Arrays(VLAs)
- Using Flexible Array Members
1. C malloc() method
In C, the "malloc" or "memory allocation" method is used to allocate a single huge block of memory with the specified size dynamically. It returns a void pointer that can be cast into any other type of pointer. Because it does not initialize memory at runtime, each block is initially set to the default garbage value.
Syntax
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate 400 bytes of RAM because int is 4 bytes long. Pointer ptr holds the address of the allocated memory's first byte.
If space is insufficient, allocation fails and returns a NULL pointer.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the Array are: 1, 2, 3, 4, 5,
2. C calloc() method
In C, the "calloc" or "contiguous allocation" method is used to allocate a specified number of blocks of memory of the specified type dynamically. It's fairly similar to malloc(), but it has two key differences:
It sets the default value for every block to 0.
In comparison to malloc(), it has two parameters or arguments.
Syntax
ptr = (cast-type*)calloc(n, element-size);
here, n is the num of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements, each with the size of the float.
If space is insufficient, allocation fails, and it returns a NULL pointer.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter total number of elements present in an array: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements in an array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output
Enter the total number of elements present in an array: 5
Memory successfully allocated.
The elements in an Array are: 1, 2, 3, 4, 5,
3. C free() method
To dynamically de-allocate memory in C, use the "free" technique. Memory allocated with the malloc() and calloc() procedures is not de-allocated on their own. As a result, anytime dynamic memory allocation occurs, the free() function is employed. It frees up memory, which helps to prevent memory waste.
Syntax
free(ptr);
Example
C example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, *ptr1;
int n, i;
n = 5;
printf("Enter the total number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
//memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
Output
Enter the total number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc memory successfully freed.
4. C realloc() method
In C, the "realloc" or "re-allocation" method is used to alter the memory allocation of a previously allocated memory dynamically. In other words, realloc can be used to dynamically re-allocate memory if the memory originally allocated with malloc or calloc is inadequate. The existing value is preserved after re-allocation of memory, and new blocks are initialized with the default garbage value.
Syntax
ptr = realloc(ptr, newSize);
Where ptr is re-allocated-allocated with new size 'newSize.'
If space is insufficient, then allocation fails and returns a NULL pointer.
Example
C example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter the total number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("Elements are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nEnter the new size of an array: %d\n", n);
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf("Elements are:");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output
Enter the total number of elements: 5
Memory successfully allocated using calloc.
Elements are: 1, 2, 3, 4, 5,
Enter the new size of an array: 10
Memory successfully re-allocatedre-allocated using realloc.
Elements are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Must Read Passing Arrays to Function in C
5. Using Variable Length Arrays(VLAs)
Variable length arrays also allow us to create an array whose size can be changed at runtime. It helps to create variable length arrays in C programming language from the C99 version upwards.
Syntax
datatype arrayname[size];
Example
#include <stdio.h>
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int array[size]; // Variable Length Array
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]); // taking input of variable length array
}
printf("The elements of the Variable Length Array are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
Output
Enter the size of the array: 3
Enter 3 elements:
5 8 12
The elements of the Variable Length Array are:
5 8 12
6. Using Flexible Array Members
Flexible array members (FAM) allow us to create an array whose size is flexible in C programming language from the C99 version upwards. The FAM is declared inside a structure along with its size, which can be changed at runtime.
Syntax
struct MyStruct {
// Other members
dataType data[]; // Flexible Array Member
};
The memory allocation of the flexible array members can be done by malloc.
struct MyStruct* myStruct = malloc(sizeof(struct MyStruct) + arraySize * sizeof(elementType));
Example
Let us look at an example of using flexible array members.
#include <stdio.h>
#include <stdlib.h>
struct MyStruct {
int length;
int data[]; // Flexible Array Member
};
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
struct MyStruct* myStruct = malloc(sizeof(struct MyStruct) + size * sizeof(int)); // Memory Allocation of Flexible Array Member
myStruct->length = size;
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &myStruct->data[i]); // Taking input of the Flexible Array Member
}
printf("The elements of the flexible array member are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", myStruct->data[i]);
}
printf("\n");
free(myStruct);
return 0;
}
Output
Enter the size of the array: 5
Enter 5 elements:
10 20 30 40 50
The elements of the flexible array member are:
10 20 30 40 50