Reputation: 95
What I would like to do here is initializing all the players' names with the empty string value ""
, I have heard it can be done at the declaration point in C99, but I'm not entirely sure how.
typedef struct data_players
{ char name[25];
int hp;
int mana;
int id;
}player;
player player_list[10]
In this case how should I proceed?
Upvotes: 0
Views: 355
Reputation: 1489
struct data_players
{ char name[25];
} player = "";
or
struct data_players
{ char name[25];
} player = { "" };
This initializes the first member of the structure at declaration time. If there are more members, separate them with comma. One more thing. Your struct should not be type-defined at declaration time to do that kind of initialization.
if you have an array of structures and you want to initialize them in C99 you can use "designated initializer" at declaration time.
player arr [2] = { {.name = ""}, {.name = ""} };
This will initialize arr[0]
and arr[1]
's name members to a null string. Though I see not much sense in it as it defaults to a null string anyway.
Upvotes: 3
Reputation: 2902
At declaration time, you initialize structs with {}
like this:
player player_list[10] = {{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0},{"", 0, 0, 0}};
Note that any skipped initializers will default to zero, so if you are always initializing the entire array to zero, this will suffice:
player player_list[10] = {0};
Also note that if player_list
is a global or a static variable, it will automatically be initialized to all zeroes. As if you called
memset(player_list, 0, sizeof(player_list));
at program start.
Upvotes: 2