为什么下面的代码会产生编译时错误?我似乎不明白为什么类型不匹配。
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/