In this blog, we will learn about dynamic array in c also known as variable sized arrays, we will learn all about them, various method to create them their use, and their application scenarios, First we will have a basic idea about fixed length array and how they are not used in some cases and why we need the dynamic array, at last, we will discuss advantages and disadvantages of a variable sized array or dynamic array in c.
Fixed Length Arrays
As the name suggests fixed length arrays have a fixed size during compilation we cannot change the size during the execution of the program. We can only set their size while writing code after that we cannot change the size. These are frequently not optimal. The majority of the time, we must construct an array of different sizes. We can certainly make an array that is the biggest size feasible, but it would be a memory waste. The solution provided by VLAs is the acceptance of runtime size for arrays.
Variable Length Array in C
The size of variable length arrays or dynamic arrays in c is calculated at runtime (still the size cannot be modified after initialization). The C99 standard introduced them to C for the first time. Later versions, however, changed it such that it was an optional feature. When they depart the scope, they are released after being allocated on the stack (just like normal arrays). We can also create the dynamic array in CPP as same as we create a dynamic array in c but we also have other methods to create a dynamic array in CPP.
Introduction to Dynamic Array in C
Not as many higher level languages like python and javascript provide inbuilt dynamic arrays but dynamic array in c is not an inbuilt function but c provides some features or methods to use dynamic array in c. These are the arrays that are resizable and can be accessed randomly. Dynamic array in c or dynamic array in CPP can be initialized by any size and that size can be changed further in the code. Dynamic array in c works on the heap whereas variable length array works on the stack.
Variable Length array is different from a dynamic array in c. Some differences among them are:
- Allocation: The dynamic array in c is allocated on the heap whereas the variable length array in c is allocated on the stack so they work faster compared to the dynamic array in c.
- Scope: Dynamic array in c or dynamic array in CPP does not bound by scope so can be used anywhere in the program until the memory is called using the free() function whereas the variable length array behaves as same as the normal array and is bounded by the scope.
- Performance: Variable length arrays are comparatively faster than dynamic arrays in c as we have to allocate and deallocate memory manually in the dynamic array in c or in the dynamic array in CPP.
Different Methods to Create Dynamic Array in C
There are various methods to create a dynamic array in c. Here we will see 5 methods to create a dynamic array in c++ or a dynamic array in c as the method we will use in c will also be applicable in the case of c++.
We will discuss five methods to create a dynamic array in c and these are mentioned below:
- Using the malloc() Function.
- Using calloc() Function.
- Using Variable Length Array
- Resizing array using realloc() function
- Using flexible array members.
1. Dynamic Array in C using malloc() function
In C, a single big block of memory with the requested size is dynamically allocated using the "malloc" or "memory allocation" technique. It returns a void pointer that may be cast into any other pointer type. It is included in the header file < stdlib.h>. The syntax for using the malloc() function to create a dynamic array in c is shown below:
ptr = (cast-type*) malloc(byte-size);
Example of creating a dynamic array in C using malloc() function
In this section we will use malloc function to create a dynamic array in c and will discuss the code and output of the corresponding code.
#include #include int main() { int* ptr; int size; // we will take the size of the array printf("Enter size of elements:"); scanf("%d", &size); // dynamically allocate memory using malloc() method. ptr = (int*)malloc(size * sizeof(int)); if (ptr == NULL) { printf("Memory not allocated.\n"); } else { printf("Memory successfully allocated using " "malloc.\n"); // Get the elements of the array for (int j = 0; j < size; ++j) { ptr[j] = j + 10; } // Print the elements of the array 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: Memory successfully allocated using malloc.
The elements of the array are: 10, 11, 12, 13, 14, 15,
Explanation of the above Code
In the above code we have asked the user to give the size of the array and then we are allocating the elements to the array. After setting the value of the elements of the dynamic array in c we are printing those values.
2. Dynamic Array using calloc() function.
When dynamically allocating the specified number of memory blocks of the specified type in C, the "calloc" or "contiguous allocation" technique is used. Each block is initialized with a default value of 0, and the method is used to allocate memory blocks in this way.
Using the calloc() function is comparable to using the malloc() technique to allocate memory for a dynamic array in c. When compared to malloc, calloc() differs in that it accepts multiple parameters (). The size of each element and the necessary number of elements for the dynamic array in c are given below. The array’s elements are all initialized to 0 as well.
ptr = (int*) calloc(5, sizeof(float));
Example of creating a dynamic array in C using calloc function
In this section we will use calloc function to create a dynamic array in c and will discuss the code and output of the corresponding code.
#include <stdio.h> #include <stdlib.h> int main() { // address of the block created hold by this pointer int* ptr; int size; // taking the size as input from the user printf("Enter size of elements:"); scanf("%d", &size); // allocating the memory using calloc dynamically ptr = (int*)calloc(size, sizeof(int)); // Checking for memory allocation if (ptr == NULL) { printf("Memory not allocated .\n"); } else { // Memory allocated printf("Memory successfully allocated using " "calloc.\n"); // Get the elements of the array for (int j = 0; j < size; ++j) { ptr[j] = j + 10; } // Print the elements of the array 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: Memory successfully allocated using calloc.
The elements of the array are: 10, 11, 12, 13, 14, 15,
Explanation of the above code
In the above code we have asked the user to give the size of the array and then we are allocating the elements to the array. After setting the value of the elements of the dynamic array in c we are printing those values.
3. Dynamically resizing Dynamic Array in C using realloc() function.
To dynamically change the memory allocation of previously allocated memory in C, use the "realloc" or "re-allocation" technique. In other words, if the memory originally allocated with malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. After re-allocating memory, the current value is kept, and new blocks are initially started with trash.
ptr = realloc(ptr, newSize);
Example of resizing a dynamic array in C using realloc() function
In this example we will see how we can change the size of a dynamic array in c after allocating all the elements to it and then after changing the size again allocating new values to the elements.
Code Implementation:
#include #include int main() { // address of the block created hold by this pointer 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"); } // inserting elements for (int j = 0; j < size; ++j) { ptr[j] = j + 10; } printf("The elements of the array are: "); for (int k = 0; k < size; ++k) { printf("%d, ", ptr[k]); } printf("\n"); size = 15; int *temp = ptr; // using realloc ptr = realloc(ptr, size * sizeof(int)); if (!ptr) { printf("Memory Re-allocation failed."); ptr = temp; } else { printf("Memory successfully re-allocated using " "realloc.\n"); } // inserting new elements for (int j = 5; j < size; ++j) { ptr[j] = j + 100; } 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: 10, 11, 12, 13, 14,
Memory successfully re-allocated using realloc.
The new elements of the array are: 10, 11, 12, 13, 14, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
Explanation of the above code
In the above code we have first allocated the size of the array by asking the user and then assigning the values using the corresponding code we have written after that we changed the size of the dynamic array in c and then set the new values of the newly added spaces afterward and then print the answer.
4. Variable Length Arrays
Variable length arrays, also known as VLAs, are those arrays where the size of the array may be changed at runtime. It bases the memory allocation for the stack on the local scope level.
When opposed to the methods above, a variable length array has the disadvantage that once defined, its size cannot be modified.
Example of Variable Length Arrays
In this section, we will look at the example of variable size arrays and how to use them to create a dynamic array in c.
Code Implementation:
// C program to demonstrate the use of VLAs #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: Enter elements: Elements of VLA of Given Size: 5 7 9 11 23 41
Explanation of the above code
In the above example we have asked the user to give the size of the dynamic array in c and after that, we asked the user to give the elements of the array and then we printed those elements.
5. Flexible Array Members
The array that is defined inside a structure without any dimensions and whose size is flexible is known as a flexible array member. The C99 standard first included this functionality.
With the help of the malloc() method, we may regulate the size of a flexible member.
Preferably, the array inside the structure should be stated as its final member, and its size is changeable (can be changed at runtime).
In addition to the flexible array member, the structure must include at least one more named member.
Example of Flexible Array Members
Here we will see the example of flexible array members with proper code, and output followed by their explanation.
// C program to demonstrate the use of Flexible Array Member #include <stdio.h> #include <stdlib.h> // defining struct typedef struct { int len; int arr[]; } fam; int main() { // creating an array member of size 5 fam* fam1 = (fam*)malloc(sizeof(fam*) + 5 * sizeof(int)); // creating an array mebmer of size 10 fam* fam2 = (fam*)malloc(sizeof(fam*) + 10 * sizeof(int)); // inserting elements for (int i = 0; i < 5; i++) { fam1->arr[i] = i + 10; } for (int i = 0; i < 10; i++) { fam2->arr[i] = i + 100; } // printing elements 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:
10, 11, 12, 13, 14,
Array of size 10:
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
Explanation of the above code
In the above example we have created two arrays of size 5 and 10 respectively and then we have assigned the values to the elements of the value after that we have printed both the arrays to show that the assigned values are assigned properly to the elements.
Advantages of a Dynamic Array in C
- They can be resized at runtime, which allows for more efficient memory usage and flexibility in terms of the size of the array.
- They can be initialized and accessed using standard array notation, making them easy to use and understand.
- They allow for easy dynamic memory allocation, which can be useful in situations where the size of an array needs to be determined at runtime.
- They can be used in conjunction with other data structures such as linked lists, making them a powerful tool for building more complex algorithms and data structures.
- They are also faster than linked-list-based data structures in certain applications, like when memory is not a concern and cache hit ratio is high.
Disadvantages of a Dynamic Array in C
- They can lead to fragmentation of memory if elements are frequently added and removed, which can decrease performance.
- They require additional memory overhead for memory management and bookkeeping.
- They can be less efficient in terms of time complexity for certain operations such as insertion and deletion, as these operations may require moving elements around in memory.
- They can be less efficient in terms of cache performance when compared to static arrays, due to the potential for cache misses when elements are spread out in memory.
- They are not thread-safe, meaning they can’t be accessed by multiple threads simultaneously.
Conclusion
In the above blog we have studied dynamic arrays in c starting with fixed-size and variable-sized arrays after that a detailed explanation of dynamic arrays in c and dynamic arrays in CPP. Then we discussed many methods to create a dynamic array in c with their code and explanation and at last, we ended with the advantages and disadvantages of a dynamic array in c.