here is the code
struct point_tag {
int x;
int y;
};
typedef struct point_tag Point;
int main(void)
{
Point pt[] = { {10,20}, {30, 40}, {50,60}};
pt[0] = {100,200};
}
当我执行 pt[0] = {100, 200}
时,编译器一直提示
error:expected expression before '{' token
虽然我不太明白。 { token 赋值运算符(=)之前的表达式不是吗?
我不明白为什么作业会成为问题。地址 pt 处的值指的是一个 Point 数组。我只是将第 0 个点设置为这个新点,我知道以 {100,200}
这样的格式分配结构是合法的,其中该数组中的元素只是字段。
最佳答案
对于赋值,将值类型转换为 Point 类型,使其成为 compound literal :
pt[0] = (Point){100,200};
Live code使用 gcc
这相当于
{
Point temp = {100,200};
pt[0] = temp;
}
附注复合文字在旧的严格 C89 兼容编译器中不可用。它在 C89 的 GCC 中可用作为扩展,在 C99 中复合文字是核心功能。
关于c - 为什么这个结构赋值数组不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646179/