rickylance
rickylance

Reputation: 67

Error in initializing structure variables

Okay, so this isn't actually the code I was working on. This is an oversimplified code extract that produces the exact same error. Thus, I thought if I could learn why I am getting errors with the simplified code, then I could apply it to my actual code. Thanks for any help/advice in advance!

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

Upvotes: 0

Views: 56

Answers (3)

midor
midor

Reputation: 5557

The correct syntax to do this is:

struct fruit f;
f.apples = 1;
f.oranges = 2;
f.strawberries = 3;

or using direct initialization:

struct fruit f = {1, 2, 3};

or in C99 upwards, using designated initializers:

struct fruit f = {
    .apples = 1,
    .oranges = 2, 
    .strawberries = 3,
};

Upvotes: 1

msc
msc

Reputation: 34678

use this:

 struct fruit fruit;

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

or

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

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

First of all, you cannot initialize a struct type variable with an int value anyway, you have to use either a brace-enclosed initializer, or initialize each member explicitly.

That said,

struct fruit applies 
struct fruit oranges 
struct fruit strawberries 

is not how you define a variable of type struct fruit and access the members. The correct way would be

 struct fruit f;
 f.apples = x;
 f.oranges = y;
 f.strawberries= 4;

or, a more precise way,

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

or, even cutting down the intermediate variables,

  struct fruit f = {1,2,4};     

Upvotes: 1

Related Questions