首页 > 解决方案 > 是否可以像创建整数数组一样创建字符串数组?

问题描述

我正在尝试通过执行以下操作来创建一个字符串数组:

#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]);
    }
}

我认为这是创建数组的方法之一,但是当我尝试编译时,我得到error: use of undeclared identifierapple,和. 但是,当我用整数尝试同样的事情时:bearcardduck

#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]);
    }
}

它可以顺利编译和运行。使用这种方法根本不可能创建一个字符串数组,还是我错过了其他东西?任何帮助将非常感激。

标签: arraysccs50c-stringsundeclared-identifier

解决方案


字符串必须用 引用"

#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]);
    }
}

推荐阅读