在对象中分配字符数组时出现错误。如何解决此错误?
typedef struct car {
int id;
char *name;
int price;
char *colors[5];
} car;
int main()
{
car obj;
obj.id = 5;
obj.name = "honda city zx";
obj.price = 1500;
obj.colors = {"red", "blue", "black"}; // Line 17
return 0;
}
错误:
prtemp.c: In function ‘main’:
prtemp.c:17:18: error: expected expression before ‘{’ token
obj.colors = {"red", "blue", "black"};
最佳答案
数组没有赋值运算符。所以这句话
obj.colors = {"red", "blue", "black"};
是无效的。你必须写
obj.colors[0] = "red";
obj.colors[1] = "blue";
obj.colors[2] = "black";
obj.colors[3] = NULL;
obj.colors[4] = NULL;
另一种方法是在创建对象时对其进行初始化。
car obj =
{
5, "honda city zx", price = 1500, {"red", "blue", "black" }
};
或者,您可以使用所谓的指定初始化。
car obj =
{
.id = 5, .name = "honda city zx", .price = 1500, .colors = { "red", "blue", "black" }
};
关于c - 错误: expected expression before ‘{’ token while assigning a character array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60148256/