In C programming, programmers have to write the programs to collect the data in the form of strings from the users. This data can be collected from the user either using the static memory or the dynamic memory. The malloc() function is used to collect data in the arrays and store this data in the dynamic memory. We used dynamic memory because we don’t know about the user requirements. If we use static memory then either we have to face a shortage of memory or the memory will be free and of no use.
We can take the input of strings from the user to create an array using the malloc() function and this is explained in detail in the article.
How to create an array of strings using the malloc() in c Programming
An array is used to store multiple data of the same data type. We can take the input of strings from the user in an array, store the array on the dynamic memory (using malloc() function) so that it can be allocated the memory according to the space needed by the program in its execution, and in the end, this array’s data can be utilized. To understand this, we will create a text file with the name,mycodefile.c and type the code given below:
printf("Please type the size of array: \n");
printf("Enter the strings:\n");
printf("Your strings were: \n");
We are using the execution of the code in Linux, so we have to use the gcc compiler to compile the file, mycodefile.c, for this purpose use the command:
$ gcc mycodefile.c -o mycodefile
Once the file has been compiled without generating any errors and warnings, execute the file using the command:
The explanation of the above code is:
- We included the three libraries; stdlib.h(for using the dynamic memory functions), stdio.h(for using the input and output functions), and strings.h(for using the string functions)
- Then we declared the two variables “size” and “integer” and take the size of the array from the user and store the value in size
- Declared the two arrays; array_i and a pointer array str_array (* is used for the pointer). The pointer array is used to assign towards the memory location
- Took the strings from the user and save them in the array_i (size 100 means that it can take only 100 characters) with the help of for loop
- Used the malloc() function to allocate the memory on the heap. We used the strlen() function to calculate the length of the input array so that size of memory can be allocated on the heap
- Copied the elements of the array array_i in str_array using the strcpy() function
- And finally, with the help of for loop, we displayed the elements store in the str_array
The strings are used in many programs for example creating a list of football players and taking a food order in a restaurant. It is recommended to use dynamic memory for storing the values for the proper memory utilization and optimization. In this write-up, we have discussed the method to take the inputs of strings, save them in an array using malloc() function in C programming and display the array.