arraysccs50c-stringsundeclared-identifier

Is it possible to create an array of strings in the same way as one can create an array of integers?


I'm trying to create an array of strings, by doing the following:

#include <stdio.h>
#include <cs50.h>

string words[] = {apple, bear, card, duck};

int main(void)
{
    for(int i = 0; i < 4; i++)
    {
        printf("%s", words[i]);
    }
}

I thought this was one of the ways that one could create an array, but when I try to compile, I get the error error: use of undeclared identifier for apple, bear, card and duck. However, when I try the same thing with integers:

#include <cs50.h>
#include <stdio.h>

int numbers[] = {1, 2, 3, 4};

int main(void)
{
    for(int i = 0; i < 4; i++)
    {
        printf("%i", numbers[i]);
    }
}

it compiles and runs without a hitch. Is it simply not possible to create an array of strings using this method, or is there something else I have missed? Any help would be much appreciated.


Solution

  • The strings must be quoted with ".

    #include <stdio.h>
    #include <cs50.h>
    
    const char *words[] = {"apple", "bear", "card", "duck"};
    
    int main(void)
    {
        for(int i = 0; i < 4; i++)
        {
            printf("%s", words[i]);
        }
    }