c - 将数组分配给 C 中的结构值

标签 c arrays pointers struct

对于家庭作业,我们正在研究 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 处定义了上述常量。看看它们有什么,该结构包含 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” 有或没有指针……所以我不确定我应该如何分配那个变量?帮助将不胜感激!

最佳答案

您不能使用 = 分配给数组。参见 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"};

关于c - 将数组分配给 C 中的结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425467/

相关文章:

c - 通过低级 I/O 读取结构

c++ - 从对象数组中选择一个随机对象

c - 与 IEEE-754 相比,内存中的浮点位模式按位反转了吗?

c++ - 将一个指针分配给另一个指针时出现段错误

c - gcc 结构中的内存对齐

android - 映射共享库时出错

php - 合并 2 个数组并合并数字键的结果

c++ - 如何将成员函数指针传递给采用常规函数指针的函数?

c - 运行时检查失败 #2 - 变量 'str' 周围的堆栈已损坏。错误?如何纠正?

javascript - Array.sort 在控制台中有效,但在 React Native 应用程序中无效