DEV Community

Cover image for Understanding Dynamic Arrays in C in Depth
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on

Understanding Dynamic Arrays in C in Depth

#c

In C programming, arrays are one of the most fundamental data structures. However, the traditional static arrays have a major limitation — their size is fixed at compile time.
What if you don’t know the number of elements you’ll need in advance?
That’s where Dynamic Arrays come in! 🧠

In this article, we’ll learn what a dynamic array is, why we use it, and how to implement it efficiently in C language.

What is a Dynamic Array?

A dynamic array is an array that can grow or shrink in size during runtime.

In simple terms:

You don’t need to decide the array size at compile time.

You can allocate memory dynamically (using malloc() or calloc()).

You can resize it later (using realloc()).

Why Do We Need Dynamic Arrays?

Imagine you’re building a program that reads numbers from the user — but you don’t know how many numbers there will be.
With static arrays, you’d have to guess a maximum size.
With dynamic arrays, you can allocate memory as needed, and expand when necessary.

Benefits:

Efficient memory usage

Flexible and scalable

Perfect for variable-sized data (like input lists, strings, etc.)

Core Functions for Dynamic Memory in C

1 - malloc() Allocates a block of memory of a given size
2 - calloc() Similar to malloc but also initializes memory to zero
3 - realloc() Changes the size of previously allocated memory
4 - free() Releases the allocated memory

Implementation: Dynamic Array in C

Let’s write an optimized and reusable version of a dynamic array implementation.

🔹 Step 1: Include Required Headers

#include <stdio.h>
#include <stdlib.h>
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the Dynamic Array Structure

We’ll create a structure that holds:

1 - The pointer to the array

2 - The total capacity

3 - The current size (number of elements actually stored)

typedef struct {
    int *data;
    size_t size;
    size_t capacity;
} DynamicArray;
Enter fullscreen mode Exit fullscreen mode

Step 3: Initialize the Dynamic Array

void initArray(DynamicArray *arr, size_t initialCapacity) {
    arr->data = (int *)malloc(initialCapacity * sizeof(int));
    arr->size = 0;
    arr->capacity = initialCapacity;
}
Enter fullscreen mode Exit fullscreen mode

This function initializes the array with a given capacity.

Step 4: Insert Elements (With Auto-Resizing)

Whenever the array is full, we’ll double its capacity automatically using realloc() for better performance.

void insert(DynamicArray *arr, int value) {
    if (arr->size == arr->capacity) {
        arr->capacity *= 2;
        arr->data = (int *)realloc(arr->data, arr->capacity * sizeof(int));
        if (arr->data == NULL) {
            printf("Memory reallocation failed!\n");
            exit(1);
        }
    }
    arr->data[arr->size++] = value;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Delete an Element (Optional)
We can also implement deletion by shifting elements.

void deleteAt(DynamicArray *arr, size_t index) {
    if (index >= arr->size) return;
    for (size_t i = index; i < arr->size - 1; i++) {
        arr->data[i] = arr->data[i + 1];
    }
    arr->size--;
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Print the Array

void printArray(const DynamicArray *arr) {
    printf("Array elements: ");
    for (size_t i = 0; i < arr->size; i++) {
        printf("%d ", arr->data[i]);
    }
    printf("\n");
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Free the Memory
Always free allocated memory to prevent memory leaks.

void freeArray(DynamicArray *arr) {
    free(arr->data);
    arr->data = NULL;
    arr->size = 0;
    arr->capacity = 0;
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

1 - Dynamic arrays allow flexible memory allocation during runtime.

2 - Use malloc() and realloc() to manage size dynamically.

3 - Always free() memory when done to avoid leaks.

4 - This implementation can be extended for any data type (using void*).

Conclusion

Dynamic arrays give C programs flexibility and efficiency, especially when dealing with variable-size data.
While C doesn’t provide built-in dynamic arrays like C++’s std::vector, implementing your own helps you master memory management — one of the most powerful skills in systems programming. 💪

Top comments (0)