How to Create a Dynamic Array in C that Can Automatically Increase in Size

How to Create a Dynamic Array in C that Can Automatically Increase in Size

If you're working in C and need an array that can dynamically grow as you need more space, you can achieve this using dynamic memory allocation with functions like malloc, realloc, and free. This guide will walk you through the steps to create such an array, ensuring efficient memory management and minimal allocations.

Steps to Create a Dynamic Array in C

Include Necessary Headers

First, you need to include the standard library for memory allocation:

include stdio.h
include stdlib.h

Declare Variables

You'll need a pointer for the array and variables to track its size and capacity:

int* array  NULL; // Pointer to hold the dynamic array
size_t size  0;   // Current number of elements in the array
size_t capacity  1; // Initial capacity of the array

Allocate Initial Memory

Use malloc to allocate initial memory for the array:

array  malloc(capacity * sizeof(int));
if (array  NULL) {
    // Handle memory allocation failure
    fprintf(stderr, "Memory allocation failed
");
    return 1;
}

Add Elements and Resize as Needed

When adding elements, check if the current size exceeds the capacity. If it does, use realloc to increase the size of the array:

void addElement(int value) {
    if (size  capacity) {
        // Increase capacity
        capacity  2; // Double the capacity
        int* temp  realloc(array, capacity * sizeof(int));
        if (temp  NULL) {
            // Handle memory allocation failure
            fprintf(stderr, "Memory allocation failed
");
            free(array); // Free the original array
            exit(1);
        }
        array  temp; // Update the array pointer
    }
    array[size]  value; // Add the new element
    size  ; // Increment size
}

Free the Memory

When you're done with the array, free the allocated memory to avoid memory leaks:

free(array);

Example Code

Here is a complete example that demonstrates these concepts:

include stdio.h
include stdlib.h
void addElement(int* array, size_t* size, size_t* capacity, int value) {
    if (*size  *capacity) {
        *capacity  2; // Double the capacity
        int* temp  realloc(array, *capacity * sizeof(int));
        if (temp  NULL) {
            fprintf(stderr, "Memory allocation failed
");
            free(array); // Free the original array
            exit(1);
        }
        array  temp; // Update the array pointer
    }
    array[*size]  value; // Add the new element
    (*size)  ; // Increment size
}
int main() {
    int* array  NULL;
    size_t size  0;
    size_t capacity  1;
    array  malloc(capacity * sizeof(int));
    if (array  NULL) {
        fprintf(stderr, "Memory allocation failed
");
        return 1;
    }
    // Adding elements
    for (int i  0; i  10; i  ) {
        addElement(array, size, capacity, i);
    }
    // Print the elements
    for (size_t i  0; i  size; i  ) {
        printf("%d ", array[i]);
    }
    printf("
";
    // Free allocated memory
    free(array);
    return 0;
}

Explanation

Dynamic Allocation

malloc allocates memory for the array, and realloc resizes it when needed to ensure efficient memory usage.

Capacity Management

The capacity is doubled each time the array needs to grow, which is a common strategy to minimize the number of allocations.

Memory Management

Always check for memory allocation failures and free allocated memory when done to prevent memory leaks.

This approach allows you to create a dynamic array that can grow as needed, efficiently managing memory in C.