1

I'm initialising an array of structures in main(); I get an error, when I declare and assign them separately.

This is my code snippet from main();

struct item newitem[10];
newitem[0]={1,"pen",5,10};
struct item new2= {2,"ygh",9,0};

This is the error I get on line 2. The line 3 works fine, however.

[Error] expected expression before '{' token

What could be the reason?

xskxzr
  • 12,442
  • 12
  • 37
  • 77
ram
  • 437
  • 2
  • 12
  • If the third line is supposed to initialize `newitem[1]` or `newitem[2]`, it fails to do so. Why not include the initializer for `newitem[0]` in the definition of `newitem`, which has the additional merit of initializing (to zeros) all the other elements of the array of structures. `struct item newitem[10] = { { 1, "pen", 5, 10, }, };` – Jonathan Leffler Apr 24 '18 at 05:23

1 Answers1

3

You have to use compound literal:

newitem[0] = (struct item) {1, "pen", 5, 10};
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Austin Stephens
  • 401
  • 4
  • 9