初始化结构变量时出错

时间:2016-09-29 11:00:34

标签: c struct initialization initializer

好的,所以这实际上不是我正在处理的代码。这是一个过于简化的代码提取,产生完全相同的错误。因此,我想如果我能理解为什么我的简化代码会出错,那么我可以将它应用到我的实际代码中。感谢您提前提供任何帮助/建议!

#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;
}

3 个答案:

答案 0 :(得分:1)

首先,您无法初始化struct类型的int类型变量,您必须使用大括号括起初始化程序,或明确初始化每个成员。

那就是说,

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};     

答案 1 :(得分:1)

执行此操作的正确语法是:

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,
};

答案 2 :(得分:1)

使用它:

 struct fruit fruit;

 fruit.apples = {x};
 fruit.oranges = {y};
 fruit.strawberries = {4};

struct fruit fruit = {x, y, 4};