C Struct编译错误
为什么以下代码会产生编译时错误? 我似乎无法理解为什么类型不匹配。
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
sut.field[0]
是一个char[MAX_CHARS+1]
"Name, "
是一个const char*
试试这个:
strcpy(sut.field[0], "Name, ");
您正在尝试将const char *
分配给char[]
,这不是完全相同的事情。 如果您的f_string
被定义为,这将有效
typedef const char * f_string;
你在这里寻找的是
strcpy ( sut.field[0], "Name, " );
或者使用strncpy
以便指定目标缓冲区的大小。
strncpy ( sut.field[0], "Name, ", MAX_CHARS )
这样可以防止你超越你的缓冲区。
你需要使用类似的东西:
strcpy( sut.field[0],"Name, ");
除了在声明时作为初始化器,您不能像其他人那样分配字符串。
sut.field [0]的类型是大小为MAX_CHARS + 1的char数组 – 您不能将字符串指针指定给字符数组。
您需要将csv_line :: field的类型更改为const char *,或者只是将文字“Name”的字符串副本更改为目标数组。
请注意, strcpy()
和strncpy()
本身都是不安全的:第一个可能会溢出缓冲区,第二个可能会在没有NUL终止符的情况下离开它。 即使你“知道”你的字符串不会溢出,你也必须意识到这些情况。
使用辅助函数安全地执行此操作:
char * strncopy(char *dst, const char *src, int dstsize) { strncpy(dst, src, dstsize-1); dst[dstsize-1] = '\0'; return dst; }
然后:
strncopy(sut.field[0], "Name, ", sizeof sut.field[0]);
sut.field[0]
的类型确实是char [MAX_CHARS+1]
。 但是,大多数其他答案都有"Name, "
的类型错误 – 它实际上是char [7]
类型(使用sizeof "Name, "
以便于演示)。
尽管如此,您仍然无法直接将char [7]
赋值给char [MAX_CHARS+1]
。 你甚至不能直接将char [7]
分配给另一个char [7]
( 初始化与这种方式的赋值不同)。
答案可能只是使用coyping函数 – 例如,如果您确定MAX_CHARS >= 6
,那么您可以使用strcpy()
。 如果你不能确定长度是否正确,那么你可以使用strncat()
作为截断字符串副本:
sut.field[0][0] = '\0'; strncat(sut.field[0], "Name, ", MAX_CHARS);
(请注意,尽管名称不同,但strncpy()
并不适用于此,实际上很少是所需的function)。
但是,值得指出的是,如果数组包含在struct
,则可以间接分配数组(相同类型)。 这意味着以下内容将起作用(如果您有C99编译器):
typedef struct { char s[MAX_CHARS+1] } f_string; /* string for each field */ csv_line sut; sut.field[0] = (f_string){"Name, "};