gpt4 book ai didi

C 结构编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:42 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com