-2

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.

1

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

It might be useful to make a full, runnable example as well and show how to print all strings in the array.
"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."
Instead 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];.
Like @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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.