0
0
CHow-ToBeginner · 3 min read

How to Create Dynamic Array in C: Syntax and Example

In C, you create a dynamic array using malloc to allocate memory at runtime and free to release it. This allows the array size to be decided while the program runs, unlike fixed-size arrays.
📐

Syntax

To create a dynamic array in C, use malloc to allocate memory for the array elements. Use free to release the memory when done.

  • type *array = malloc(n * sizeof(type)); allocates memory for n elements of type.
  • free(array); frees the allocated memory.
c
type *array = malloc(n * sizeof(type));
// Use the array
free(array);
💻

Example

This example creates a dynamic array of integers, fills it with values, prints them, and then frees the memory.

c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 5;
    int *arr = malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    printf("Dynamic array elements:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}
Output
Dynamic array elements: 10 20 30 40 50
⚠️

Common Pitfalls

Common mistakes when using dynamic arrays in C include:

  • Not checking if malloc returns NULL, which means memory allocation failed.
  • Forgetting to free the allocated memory, causing memory leaks.
  • Accessing out-of-bounds indexes, which leads to undefined behavior.
c
#include <stdlib.h>
#include <stdio.h>

int main() {
    int n = 3;
    // Wrong: Not checking malloc result
    int *arr = malloc(n * sizeof(int));

    // Correct: Check if malloc succeeded
    if (arr == NULL) {
        printf("Failed to allocate memory\n");
        return 1;
    }

    // Use array safely
    for (int i = 0; i < n; i++) {
        arr[i] = i;
    }

    // Correct: Free memory to avoid leaks
    free(arr);
    return 0;
}
📊

Quick Reference

Remember these key points when working with dynamic arrays in C:

  • Use malloc to allocate memory dynamically.
  • Always check if malloc returns NULL.
  • Access only within allocated size.
  • Use free to release memory when done.

Key Takeaways

Use malloc to allocate dynamic array memory and free to release it.
Always check if malloc returns NULL to avoid crashes.
Do not access array elements outside the allocated range.
Free allocated memory to prevent memory leaks.
Dynamic arrays let you decide size while the program runs.