初始化结构变量时出错
Error in initializing structure variables
好的,所以这实际上不是我正在处理的代码。这是一个过于简化的代码摘录,会产生完全相同的错误。因此,我想如果我能知道为什么我在使用简化代码时会出错,那么我就可以将它应用到我的实际代码中。提前感谢任何help/advice!
#include <stdio.h>
int main()
{
struct fruit
{
int apples;
int oranges;
int strawberries;
};
int x;
int y;
int z;
x = 1;
y = 2;
z = 3;
struct fruit apples = x;
struct fruit oranges = y;
struct fruit strawberries = 4;
printf("The value is %d or %d", fruit.apples,fruit.strawberries);
return 0;
}
首先,您无论如何都不能用 int
值初始化 struct
类型变量,您必须使用大括号括起来的初始化程序,或者显式初始化每个成员。
也就是说,
struct fruit applies
struct fruit oranges
struct fruit strawberries
不是定义类型 struct fruit
的变量和访问成员的方式。正确的方法是
struct fruit f;
f.apples = x;
f.oranges = y;
f.strawberries= 4;
或者,更准确地说,
struct fruit f = {x,y,4};
或者,甚至减少中间变量,
struct fruit f = {1,2,4};
执行此操作的正确语法是:
struct fruit f;
f.apples = 1;
f.oranges = 2;
f.strawberries = 3;
或使用直接初始化:
struct fruit f = {1, 2, 3};
或者在 C99 以上版本中,使用指定的初始值设定项:
struct fruit f = {
.apples = 1,
.oranges = 2,
.strawberries = 3,
};
使用这个:
struct fruit fruit;
fruit.apples = {x};
fruit.oranges = {y};
fruit.strawberries = {4};
或
struct fruit fruit = {x, y, 4};
好的,所以这实际上不是我正在处理的代码。这是一个过于简化的代码摘录,会产生完全相同的错误。因此,我想如果我能知道为什么我在使用简化代码时会出错,那么我就可以将它应用到我的实际代码中。提前感谢任何help/advice!
#include <stdio.h>
int main()
{
struct fruit
{
int apples;
int oranges;
int strawberries;
};
int x;
int y;
int z;
x = 1;
y = 2;
z = 3;
struct fruit apples = x;
struct fruit oranges = y;
struct fruit strawberries = 4;
printf("The value is %d or %d", fruit.apples,fruit.strawberries);
return 0;
}
首先,您无论如何都不能用 int
值初始化 struct
类型变量,您必须使用大括号括起来的初始化程序,或者显式初始化每个成员。
也就是说,
struct fruit applies
struct fruit oranges
struct fruit strawberries
不是定义类型 struct fruit
的变量和访问成员的方式。正确的方法是
struct fruit f;
f.apples = x;
f.oranges = y;
f.strawberries= 4;
或者,更准确地说,
struct fruit f = {x,y,4};
或者,甚至减少中间变量,
struct fruit f = {1,2,4};
执行此操作的正确语法是:
struct fruit f;
f.apples = 1;
f.oranges = 2;
f.strawberries = 3;
或使用直接初始化:
struct fruit f = {1, 2, 3};
或者在 C99 以上版本中,使用指定的初始值设定项:
struct fruit f = {
.apples = 1,
.oranges = 2,
.strawberries = 3,
};
使用这个:
struct fruit fruit;
fruit.apples = {x};
fruit.oranges = {y};
fruit.strawberries = {4};
或
struct fruit fruit = {x, y, 4};