【问题标题】:Is it possible to create an array of strings in the same way as one can create an array of integers?是否可以像创建整数数组一样创建字符串数组?
【发布时间】:2021-05-06 07:11:13
【问题描述】:

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

#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 identifier for apple、bear、card 和 duck。但是,当我尝试用整数做同样的事情时:

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

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

【问题讨论】:

  • stackoverflow.com/a/1088667 这可能会有所帮助
  • apple 不是字符串。这是一个标识符,例如变量的名称。 "apple"(注意引号)是一个字符串文字。

标签: arrays c cs50 c-strings undeclared-identifier


【解决方案1】:

字符串必须用" 引用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    相关资源
    最近更新 更多