![]() |
VOOZH | about |
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.
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.
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.
The following program illustrates how to create a dynamic array of strings in C:
Student0 Student1 Student2 Student3 Student4
Time Complexity: O(N), where N is the number of strings in the array.
Auxiliary Space: O(N)