Choco Fernandez Choco Fernandez - 2 months ago 7
C Question

Cannot initialize an array of struct within a struct

I'm trying to create an RPG-esque inventory, my inventory contains a type 'sword' which is an array.
Here's the code for my sword struct:

typedef struct
{
char weaponName[35];
int damage;
int rarity;
float price;

} sword;


Here's the one for the inventory:

typedef struct
{
sword SwordInvent[size];
} inventory;


I tried to initialize the
SwordInvent
array in the main function but it ends up with an error.


[Error] expected expression before '{' token


main()
{
inventory inv;
inv.SwordInvent[0] = {"Paper Sword", 1, 1, 1};
}


Can anyone be kind enough to help me get out of this hole? :(

EDIT
I could not thank you all enough! I wasn't really expecting to get this much of help! Seriously, thank you!

Answer

You can't just start listing stuff inside braces and have the compiler magically figure out what you want. It doesn't work like that, except with initializers. Initializers, e.g.

const sword excalibur = { "Excalibur!", INT_MAX, INT_MAX, FLT_MAX };

are different from assignment. With initializers, it's assumed that the right-hand side is going to match the left-hand side, since it's an initializer. Also, they existed longbefore compound literals, so way back this was all you could to with = and structures.

Your code (assignment) is a bit like this:

float x;
x = 1 / 2;

This does not do a floating-point division, since 1 and 2 are both integers; the compiler does not figure out that this should have a floating point result based on the type of the left-hand side (and no, with an initializer for a float it still doesn't help, float x = 1 / 2; will not assign 0.5 but 0; end of analogy).

The same is true (kind of) for your brace-list assignment. There needs to be something on the right hand side that indicates the type of the braced list.

Thus, you need to use the compound literal syntax:

inv.SwordInvent[0] = (sword) {"Paper Sword",1,1,1};

Also, your sword is not an array, it's a struct.