Open In App

How to Create a Dynamic Array of Strings in C?

In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program's runtime. Strings are arrays of characters terminated by the null character '\0'. A dynamic array of strings will ensure to change it's size dynamically during the runtime of the program as per the user's needs. In this article, we will learn how to create a dynamic array of strings in C.

Create a Dynamic Array of Strings in C

To create a dynamic array of strings in C, we can use the concept of double pointer and dynamic memory allocation. The double pointer is the pointer that stores the memory address of another pointer. We create an array of pointers to characters (i.e. strings) and then store the address of this array in the double-pointer to characters. Each of the pointer to the character is again allocated memory based on the size of the string it is storing.

Approach

Note: We have to first free() the memory allocated to each of the pointer of the array and then free the array of pointers. Otherwise, it may lead to the memory leak.

C Program to Create a Dynamic Array of Strings

The following program illustrates how to create a dynamic array of strings in C:

// C Program to illustrate how to create a dynamic array of
// strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// define the maximum length of the string you will store in
// the array
#define MAX_STRING_LENGTH 20

int main()
{
    // Initialize a double pointer to store the array of
    // strings
    char** strings = NULL;
    // Declare the initial size of the dynamic array
    int size = 5;

    // Allocate memory for the array of strings
    strings = (char**)malloc(size * sizeof(char*));
    if (strings == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    // Allocate memory for each string and assign values
    for (int i = 0; i < size; i++) {
        // Allocate memory for each string
        strings[i] = (char*)malloc((MAX_STRING_LENGTH + 1)
                                   * sizeof(char));
        if (strings[i] == NULL) {
            fprintf(stderr, "Memory allocation failed\n");
            return 1;
        }
        // Assign values to each string
        sprintf(strings[i], "Student%d", i);
    }

    // Print the strings present in the array
    for (int i = 0; i < size; i++) {
        printf("%s\n", strings[i]);
    }

    // Free memory for each string
    for (int i = 0; i < size; i++) {
        free(strings[i]);
    }
    // Free memory for the array of pointers
    free(strings);

    return 0;
}

Output
Student0
Student1
Student2
Student3
Student4

Time Complexity: O(N), where N is the number of strings in the array.
Auxiliary Space: O(N)



Article Tags :