View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Dynamic Arrays in C: Efficient Memory Allocation Explained

Updated on 14/05/20253,391 Views

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.

What is Dynamic Array 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:

  • Allocate memory as needed instead of wasting memory with overly large static arrays.
  • Adjust the array size on the fly, especially when data grows or shrinks during program execution.
  • Manage system resources better with controlled memory allocation and deallocation.

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()`.

Methods to Create Dynamic Array in C

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: 

Dynamic Array in C Using `malloc()` Function

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()`?

  • Allocates memory at runtime based on user input or logic.
  • Enables the creation of arrays with unknown or variable size.
  • Returns a pointer to a block of uninitialized memory on the heap.

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

  • `malloc(n * sizeof(int))` allocates enough memory to store `n` integers.
  • Always check if `malloc()` returned `NULL` to avoid using invalid memory.
  • Use `free()` to deallocate memory after you're done using the dynamic array to prevent memory leaks.

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.

Dynamic Array in C Using `calloc()` Function

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()`?

  • Allocates memory at runtime, just like `malloc()`.
  • Initializes each byte of allocated memory to zero.
  • Useful when you want to start with a clean array with default values.

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);
  • `num` is the number of elements.
  • `size` is the size of each element.

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

  • `calloc(n, sizeof(int))` allocates memory for `n` integers and sets all bits to zero.
  • Unlike `malloc()`, you don't need to manually initialize the array.
  • Always check for a `NULL` return to ensure successful allocation.
  • Use `free()` to release the memory when done.

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.

Resizing Array Using `realloc()` Function

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()`?

  • Resizes memory blocks without manual copying of data.
  • Maintains the existing contents up to the new size (if increased).
  • Automatically frees and reallocates memory when necessary.
  • Enables true dynamic growth and flexibility for arrays.

Syntax

void *realloc(void *ptr, size_t new_size);
  • `ptr` is the pointer to the existing memory block.
  • `new_size` is the new total size in bytes.

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

  • Initially allocates memory for 3 integers.
  • `realloc()` resizes the memory to hold 5 integers, preserving the existing 3 values.
  • Additional inputs are then stored in the newly allocated space.
  • Always verify the pointer after calling `realloc()` as it may return `NULL`.

Using `realloc()` adds a new level of flexibility to your dynamic array in C, enabling real-time resizing without manually copying data between arrays.

Dynamic Array in C Using Variable Length Arrays (VLAs)

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?

  • Syntax is closer to regular arrays.
  • Allocated on the stack, so no need to manually `free()` the memory.
  • Useful for temporary arrays with small-to-moderate size requirements.

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

  • The size of the array `arr` is determined during runtime using user input.
  • Unlike heap-allocated dynamic arrays, VLAs are destroyed automatically when the function exits.
  • No need for `malloc()`, `calloc()`, or `free()`—memory management is implicit.

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.

Dynamic Array in C Using Flexible Array Members

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?

  • Perfect for designing composite data structures with a variable-length array inside.
  • Clean, scalable, and efficient approach for managing structured dynamic data.
  • Commonly used in system-level programming, like kernels and network buffers.

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 `DynamicArray` struct contains an integer to store the length and a flexible array member for the actual data.
  • `malloc()` allocates enough memory for the struct and the required number of integers.
  • Input is stored directly in the flexible array member `data[]`.
  • This pattern is ideal when designing APIs or components that need a mix of metadata and dynamic content.

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.

Conclusion

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.

FAQs 

1. Can you resize a dynamic array in C after it's created?

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.

2. Is it necessary to free memory after using dynamic arrays in C?

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.

3. Can you create a dynamic array of structs in C?

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.

4. What happens if you don’t check for `NULL` after using `malloc()`?

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`.

5. Can a dynamic array in C hold elements of different types?

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.

6. What is the maximum size of a dynamic array in C?

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.

7. Can dynamic arrays in C be multidimensional?

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.

8. Are dynamic arrays in C faster than static arrays?

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.

9. Can you use `sizeof()` to get the size of a dynamic array?

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.

10. How do you initialize a dynamic array with specific values in C?

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()`.

11. What is the benefit of using a dynamic array over a static array in C?

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.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.