C 结构编译错误

标签 c struct compiler-errors

为什么下面的代码会产生编译时错误?我似乎不明白为什么类型不匹配。

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

/*
 * A parsed CSV line, with the number of fields and upto MAX_FIELDS themselves.
*/

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

....

csv_line sut;
sut.field[0] = "Name, "; //Compile-time error.

错误是:

error: incompatible types in assignment

最佳答案

您正在尝试将 const char * 分配给 char[],这不是一回事。如果您的 f_string 定义为

,这将起作用
typedef const char * f_string;

你要找的是

strcpy ( sut.field[0], "Name, " );

或者使用strncpy 这样您就可以指定目标缓冲区的大小..

strncpy ( sut.field[0], "Name, ", MAX_CHARS )

这将防止您超出缓冲区。

关于C 结构编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4362801/

相关文章:

将具有动态数组的结构复制到c中的缓冲区中

java - 需要有关编译器错误的帮助

c - dladdr() 出现问题的宏

c - 从 H.264 比特流中提取运动 vector

ios - Swift:使用 UISearchController/Predicates 过滤结构数组

go - 在编写可能最终被传递给任何类型的结构的函数时,我可以使用接口(interface)作为参数吗?

c++ - 创建列表/节点类程序的模板版本时遇到麻烦

c# - 将程序集添加到gac时csharpcodeprovider无法编译

c - 由于 HTTP header 中的奇怪字符,发送数据失败

c - 当我在 scanf 中输入字符而不是整数值时出现意外结果