How store multiple string or create an array of strings in C, by using 1D array?
The short answer is: You can't
A string in C is by itself a char array (with a zero termination) so there is no way to have multiple strings in a 1D array.
You can make it a 2D array like:
int main()
{
// Make a 2D array to store
// 4 strings with 9 as max strlen
char str[4][10] = {"Linux", "Ubuntu", "Arch", "Void"};
for (int i=0; i<4; ++i) printf("%s\n", str[i]);
return 0;
}
Another approach is to use a 1D array of char pointers to string literals - like:
int main()
{
// Make a 1D array to store
// 4 char pointers
char *str[4] = {"Linux", "Ubuntu", "Arch", "Void"};
for (int i=0; i<4; ++i) printf("%s\n", str[i]);
return 0;
}
but notice that the strings are not saved in the array. The compiler place the strings somewhere in memory and the array just holds pointers to those strings.
Also notice that in the second example you are not allowed to modify the strings later in the program. In the first example you are allowed to change the strings after the initialization, e.g. doing strcpy(str[0], "Centos");
BTW: This may be of interrest Are string literals const?