0

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
BlueKhakis
  • 293
  • 1
  • 8
  • 1
    https://stackoverflow.com/a/1088667 this might help – sachco Feb 02 '21 at 05:26
  • 2
    `apple` is not a string. It's an identifier, like e.g. the name of a variable. `"apple"` (note the quotes) is a string literal. – bolov Feb 02 '21 at 05:26

1 Answers1

4

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]);
    }
}
Robert
  • 2,711
  • 7
  • 15