For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
When you're working with arrays in C, one major limitation you quickly run into is their fixed size. Traditional arrays require you to declare their size at compile-time, which isn't always practical. What if you're dealing with a dataset that grows during runtime, like user inputs or data fetched from a file? That's where a dynamic array in C steps in as a powerful solution.
But, before you begin, it’s always recommended to first understand an array in C. Then, move to a dynamic array, which is an array whose size can be determined and modified during the execution of a program. This offers tremendous flexibility and is especially useful in real-world application development, which are taught in top-rated software development courses.
In this blog, we’ll explore everything you need to know about implementing and working with a dynamic array in C. From malloc() to realloc(), and from VLAs to flexible array members, you'll walk away with a complete understanding of how to manage memory and build scalable programs in C.
A dynamic array in C is an array that allows you to change its size during the runtime of the program. Unlike static arrays, where the size is fixed and defined at compile-time, dynamic arrays are created using pointers in C and dynamic memory allocation functions. This is a crucial feature when dealing with scenarios where the amount of data is not known beforehand.
In C, memory for a dynamic array in C is typically allocated on the heap using functions in C like `malloc()`, `calloc()`, or `realloc()`. You also have options like Variable Length Arrays (VLAs) and flexible array members, which provide more ways to handle dynamic data.
Here are a few key advantages of using a dynamic array in C:
Build a high-paying career path with the following full-stack development courses:
A simple static array declaration looks like this:
int arr[10]; // Fixed size array with 10 elements
But with a dynamic array in C, you can do this:
int *arr = malloc(10 * sizeof(int)); // Dynamic array of 10 integers
Here, memory is allocated at runtime, and you can easily resize or free it when you're done—giving you complete control.
In the next sections, we’ll explore different methods to create a dynamic array in C, starting with `malloc()`.
Creating a dynamic array in C can be done using several approaches, depending on your specific use case and requirements. Each method provides a different level of control over memory management and has its pros and cons.
Let’s take a quick overview of the main techniques to create a dynamic array in C:
1. Using `malloc()` Function
The `malloc()` function allocates a specified number of bytes in memory and returns a pointer to the beginning of the block. It's uninitialized memory, so you’ll need to assign values manually.
2. Using `calloc()` Function
Similar to `malloc()`, but initializes the memory block to zero. This is useful when you want to start with a clean slate.
3. Using `realloc()` Function
When the existing memory isn’t enough, you can resize the allocated memory using `realloc()`. It can increase or decrease the memory block while preserving existing data.
4. Using Variable Length Arrays (VLAs)
Introduced in C99, VLAs allow arrays with sizes determined at runtime. However, they're allocated on the stack and have some limitations in portability and size.
5. Using Flexible Array Members
These are arrays with no fixed size declared inside a structure. They’re useful when you're designing data structures that require a dynamically-sized member.
Each method serves a specific purpose, and understanding when to use which can significantly enhance your C programming skills. In the next section, we'll start with the most common method: creating a dynamic array in C using `malloc()`.
Additionally, there many other functions in C, which you must learn about, such as:
One of the most common methods to create a dynamic array in C is by using the `malloc()` function. Short for "memory allocation," `malloc()` is part of the C standard library (`stdlib.h`) and allows you to allocate memory during program execution, making your code more flexible and memory-efficient.
Why Use `malloc()`?
Example: Creating a Dynamic Array Using `malloc()`
This example demonstrates how to create a dynamic array in C using `malloc()`, take user input, and display the contents.
#include <stdio.h>
#include <stdlib.h> // Required for malloc() and free()
int main() {
int *arr; // Pointer to hold the base address of the dynamic array
int n; // Number of elements
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory dynamically for n integers
arr = (int *)malloc(n * sizeof(int));
// Check if malloc() successfully allocated memory
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit if memory allocation failed
}
// Taking input into the dynamic array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Displaying the contents of the dynamic array
printf("You entered:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Freeing the allocated memory
free(arr);
return 0;
}
Output (Example)
Enter number of elements: 4
Enter 4 integers:
5 10 15 20
You entered:
5 10 15 20
Explanation
This is a fundamental example of how a dynamic array in C can be created using `malloc()`. Next, we’ll look at another similar function—`calloc()`—which adds automatic initialization to the mix.
Another reliable way to create a dynamic array in C is by using the `calloc()` function. Like `malloc()`, `calloc()` is part of the C standard library and is used to allocate memory during runtime. The primary difference is that `calloc()` also initializes the allocated memory to zero, which can help avoid bugs from uninitialized values.
Why Use `calloc()`?
To know more about runtime compilation, you should know the difference between a compiler and an interpreter in C.
Syntax
void *calloc(size_t num, size_t size);
Example: Creating a Dynamic Array Using `calloc()`
In this example, we'll use `calloc()` to create a dynamic array in C, populate it, and display the data.
#include <stdio.h>
#include <stdlib.h> // Required for calloc() and free()
int main() {
int *arr; // Pointer for the dynamic array
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers and initialize to 0
arr = (int *)calloc(n, sizeof(int));
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Show the initialized values (all should be 0)
printf("Initial array values (should be all 0):\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Update the array with user input
printf("\nEnter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display updated array
printf("Updated array values:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the dynamically allocated memory
free(arr);
return 0;
}
Output (Example)
Enter number of elements: 5
Initial array values (should be all 0):
0 0 0 0 0
Enter 5 integers:
3 6 9 12 15
Updated array values:
3 6 9 12 15
Explanation
Using `calloc()` is a great option when default initialization matters, and it’s especially useful in large applications where uninitialized memory could lead to bugs or unpredictable behavior in your dynamic array in C.
In real-world applications, it's common to allocate a dynamic array in C with an initial size and then realize you need more space. That’s where the `realloc()` function becomes essential. It allows you to resize an existing dynamic array without losing the data already stored in it.
Why Use `realloc()`?
Syntax
void *realloc(void *ptr, size_t new_size);
Example: Expanding a Dynamic Array Using `realloc()`
This example demonstrates how to start with a small dynamic array, fill it, then expand it using `realloc()`.
#include <stdio.h>
#include <stdlib.h> // Required for malloc(), realloc(), and free()
int main() {
int *arr;
int n = 3;
// Allocate initial memory for 3 integers
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Initial memory allocation failed.\n");
return 1;
}
// Fill initial array
printf("Enter 3 integers:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display initial contents
printf("Initial array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Resize the array to hold 5 integers
n = 5;
arr = (int *)realloc(arr, n * sizeof(int));
if (arr == NULL) {
printf("\nMemory reallocation failed.\n");
return 1;
}
// Fill the new elements
printf("\nEnter 2 more integers:\n");
for (int i = 3; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the final array
printf("Expanded array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}
Output (Example)
Enter 3 integers:
10 20 30
Initial array:
10 20 30
Enter 2 more integers:
40 50
Expanded array:
10 20 30 40 50
Explanation
Using `realloc()` adds a new level of flexibility to your dynamic array in C, enabling real-time resizing without manually copying data between arrays.
Variable Length Arrays (VLAs) were introduced in the C99 standard and offer a simple way to declare arrays with sizes determined at runtime. Unlike other dynamic memory techniques, VLAs are allocated on the stack, not the heap. This makes them faster to allocate but also limits their size and lifetime.
Although VLAs provide a convenient syntax, they come with trade-offs. For instance, not all compilers support them (especially in strict ANSI C mode), and the allocated memory is automatically released when the array goes out of scope.
Also read about variables in C to strengthen your C fundamentals.
Why Use VLAs?
Example: Creating a Dynamic Array in C Using VLAs
This example demonstrates how to declare and use a dynamic array in C with VLAs.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare a variable length array (VLA)
int arr[n]; // Size is determined at runtime
// Input elements into the VLA
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the array elements
printf("You entered:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output (Example)
Enter the number of elements: 4
Enter 4 integers:
7 14 21 28
You entered:
7 14 21 28
Explanation
VLAs are a lightweight way to implement a dynamic array in C, especially when performance matters and you don't need to keep the array after the function returns. However, their stack-based nature means they are less suited for large data structures or long-lived arrays.
Flexible Array Members (FAMs) are a feature introduced in the C99 standard that allow the last element of a `struct` to be an array without a specified size. This is useful when you want to create a data structure where one member—the flexible array—can vary in size depending on runtime requirements.
Unlike VLAs, flexible array members are stored in heap memory, not on the stack. You must dynamically allocate the memory for the entire structure, including the flexible array, making this approach highly adaptable and memory-efficient.
Why Use Flexible Array Members?
Syntax
The flexible array is always the last member of the `struct`, and it’s declared with empty square brackets `[]`.
Example: Creating a Dynamic Array in C Using Flexible Array Members
#include <stdio.h>
#include <stdlib.h>
// Define a struct with a flexible array member
typedef struct {
int length;
int data[]; // Flexible array member (must be last)
} DynamicArray;
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory for the structure + n integers
DynamicArray *arr = (DynamicArray *)malloc(sizeof(DynamicArray) + n * sizeof(int));
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Set the length and take input
arr->length = n;
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr->data[i]);
}
// Print the values
printf("Stored values:\n");
for (int i = 0; i < arr->length; i++) {
printf("%d ", arr->data[i]);
}
// Free the memory
free(arr);
return 0;
}
Output (Example)
Enter the number of elements: 3
Enter 3 integers:
8 16 32
Stored values:
8 16 32
Explanation
The flexible array member is a sophisticated and efficient way to handle a dynamic array in C, especially when the array needs to be part of a larger data structure.
Mastering dynamic arrays in C is essential for efficiently managing memory in applications with varying data sizes. We’ve explored key techniques such as using malloc() and calloc() for dynamic allocation, and realloc() for resizing arrays, providing flexibility when the size of the array is unknown at compile time. Additionally, we've covered advanced methods like Flexible Array Members (FAMs) and 2D dynamic arrays, each offering unique advantages depending on the use case.
Whether you are dealing with simple arrays or complex data structures, choosing the right dynamic array technique will help you build more efficient and scalable programs. Always ensure to manage memory properly, using free() to release allocated memory and avoid memory leaks. With these dynamic memory management strategies in your toolkit, you can optimize your C programs to handle a wide range of data processing tasks.
Yes, dynamic arrays in C can be resized using the `realloc()` function. This function allows you to increase or decrease the size of an existing array, adjusting the memory allocation accordingly. It’s crucial to handle errors if `realloc()` fails, as it may return `NULL` if memory allocation isn’t possible.
Yes, it’s crucial to free memory after using dynamic arrays in C. Failure to deallocate memory leads to memory leaks, where the program consumes more and more memory without releasing it. Using the `free()` function ensures that memory is returned to the system for future use.
Yes, a dynamic array of structs can be created in C. You would use `malloc()` or `calloc()` to allocate memory for an array of structs. Each element of the array will be a struct, and you can access or modify its members just like with a statically declared struct array.
If you don’t check for `NULL` after using `malloc()`, your program may attempt to access invalid memory, leading to undefined behavior, crashes, or segmentation faults. Always verify that `malloc()` successfully allocated memory by checking if the returned pointer is `NULL`.
No, dynamic arrays in C are homogeneous, meaning they can only store elements of the same type. If you need to store different types of data, you can either use structs to combine multiple types or consider using pointers and handling memory manually.
The maximum size of a dynamic array in C depends on the system's memory limit and the data type you're using. It’s constrained by the available heap memory, which can be quite large, but extremely large arrays may cause memory allocation failures, especially on systems with limited resources.
Yes, dynamic arrays in C can be multidimensional, including 2D arrays. To create a 2D dynamic array, you can allocate an array of pointers for rows and then allocate each row individually. Alternatively, you can allocate a single block of memory and calculate indices manually.
Dynamic arrays in C are not inherently faster than static arrays. In fact, they may incur overhead due to memory allocation and deallocation. However, they offer flexibility when dealing with data whose size is unknown at compile time, making them more efficient in certain use cases that require resizing.
No, `sizeof()` does not work with dynamically allocated arrays to determine their size. It only works with the pointer’s size. Since dynamic arrays in C don't store their size, you need to track the size manually or use other methods to determine how much memory was allocated.
To initialize a dynamic array with specific values in C, you can either use a loop to assign values manually after memory allocation or use `calloc()`, which automatically initializes all elements to zero. For other specific values, a loop is typically necessary after using `malloc()`.
The primary benefit of using a dynamic array over a static array in C is flexibility. Dynamic arrays allow you to allocate memory at runtime based on the program's needs. This eliminates the limitations of static arrays, which require predefined sizes and cannot be resized during program execution.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.