I've seen some videos where a 2D array is created to store the strings, but I wanted to know if it is possible to make a 1D array of strings.
Asked
Active
Viewed 327 times
-2
-
1https://stackoverflow.com/a/27705098/17856705 – Computable Jul 11 '22 at 23:47
1 Answers
1
NOTE: In C, a string is an array of characters.
//string
char *s = "string";
//array of strings
char *s_array[] = {
"array",
"of",
"strings"
};
Example
#include <stdio.h>
int main(void)
{
int i = 0;
char *s_array[] = {
"array",
"of",
"strings"
};
const int ARR_LEN = sizeof(s_array) / sizeof(s_array[0]);
while (i < ARR_LEN)
{
printf("%s ", s_array[i]);
i++;
}
printf("\n");
return (0);
}

Maxwell D. Dorliea
- 1,086
- 1
- 8
- 20
-
It might be useful to make a full, runnable example as well and show how to print all strings in the array. – Gabriel Staples Jul 12 '22 at 00:05
-
2"In C, a string is an array of characters." --> better as "In C, a string is an array of characters with a terminating null character.". C lib defines it as: "A _string_ is a contiguous sequence of characters terminated by and including the first null character." – chux - Reinstate Monica Jul 12 '22 at 01:35
-
3Instead of `const int ARR_LEN = 3;`, could determine the count from `s_array{}` with `const int ARR_LEN = sizeof s_array / sizeof s_array[0];`. – chux - Reinstate Monica Jul 12 '22 at 01:37
-
1Like @chux-ReinstateMonica said, you can get the array length from the array. Here is a macro I like to use: `#define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))`. Example usage: search this file for `ARRAY_LEN(`: [array_2d_practice.c](https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/array_2d_practice.c). – Gabriel Staples Jul 12 '22 at 17:55
-
`s` isn't a string, it is a pointer to (the first element of) a string. Similarly, `s_array` isn't an array of strings, it is an array of pointers. One reason that this matters is because attempts to modify the strings referenced by `s` or by the pointers in `s_array` lead to undefined behavior. You could create a string with `char s[] = "string";`, or an array of strings with `char s_array[][4] = { "abc", "123" };`. These strings can be modified. – ad absurdum Jul 24 '23 at 13:43