0

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
rickylance
  • 67
  • 9
  • 1
    There are *so* many errors here: it seems to be the best course of action is for you to read a good book. K & R is unbeatable IMHO. – Bathsheba Sep 29 '16 at 11:03
  • `struct fruit fruit = {x, y, 4};` – BLUEPIXY Sep 29 '16 at 11:04
  • I am actually using "The C Programming Language" book lolol. They initialized a struct with int values too. – rickylance Sep 29 '16 at 11:06
  • K&R is a horrible, completely outdated book, full or errors and bad programming practice. You can however get a good laugh if you read chapter 6 about structures: "The main change made by the ANSI standard is to define structure assignment - structures may be copied and assigned to, passed to functions, and returned by functions. This has been supported by most compilers for many years, but the properties are now precisely defined. Automatic structures and arrays may now also be initialized." Wow! The future is here! I'm gonna get a copy of this ANSI C thing! – Lundin Sep 29 '16 at 11:38

3 Answers3

1

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};     
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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,
};
midor
  • 5,487
  • 2
  • 23
  • 52
1

use this:

 struct fruit fruit;

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

or

struct fruit fruit = {x, y, 4};
msc
  • 33,420
  • 29
  • 119
  • 214