【问题标题】:Assigning Array to a Struct value in C将数组分配给C中的结构值
【发布时间】:2011-05-24 10:51:30
【问题描述】:

对于家庭作业,我们正在研究 CSV 解析器。我正在努力让事情正常进行,但我遇到了一个问题。我似乎无法为结构中的“字段”值赋值。在他们提供的代码中,他们有:

typedef char f_string[MAX_CHARS+1] ;    /* string for each field */

    typedef struct {
        int nfields;                        /* 0 => end of file */
        f_string field[MAX_FIELDS];         /* array of strings for fields */
    } csv_line ;

上面的常量定义在 20 和 15。看看它们有什么,struct 包含和 int,它包含一个数组,该数组应该用他们之前定义的 f_string typedef 填充。好吧,酷。我试着这样做:

f_string test = "Hello, Bob";
f_string testAgain = "this is dumb, k?";
f_string anArray[MAX_FIELDS] = {*test, *testAgain};

csv_line aLine;
aLine.nfields = 3;
aLine.field = *anArray;

当我创建“anArray”时,如果我没有对 test 和 testAgain 的取消引用,我会收到关于在没有强制转换的情况下将整数指向指针的警告。所以我把它们留在里面。但是这条线:

aLine.field = *anArray;

返回错误:“csv.c:87: error: incompatible types in assignment”有或没有那里的指针...所以我不确定我应该如何分配该变量?帮助将不胜感激!

【问题讨论】:

    标签: c arrays pointers struct


    【解决方案1】:

    您不能使用= 分配给数组。有关更详细的说明,请参阅this question

    您需要使用strcpy(或更安全的strncpy)函数复制每个字符串:

    for (int i = 0; i < aLine.nfields; ++i)
    {
      strncpy(aLine.field[i], anArray[i], MAX_CHARS);
    }
    

    此外,您提供的测试代码不会达到您的预期。

    f_string test = "Hello, Bob";
    f_string testAgain = "this is dumb, k?";
    f_string anArray[MAX_FIELDS] = {*test, *testAgain};
    

    这将复制testtestAgain 的第一个字符。您需要执行以下操作:

    f_string test = "Hello, Bob";
    f_string testAgain = "this is dumb, k?";
    f_string anArray[MAX_FIELDS];
    strcpy(anArray[0], test);
    strcpy(anArray[1], testAgain);
    

    或者只是:

    f_string anArray[MAX_FIELDS] = {"Hello, Bob", "this is dumb, k"};
    

    【讨论】:

    • 请注意,除非数组在aLine.field[i][MAX_CHARS] 处已经有一个'\0',否则这不一定会以空值终止字符串。
    • 我意识到我上面的代码无法正常工作,并且使用您的代码,我必须将它们 strcpy 输入。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多