0

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?

2
  • You are editing the question, making answers invalid. Not a good thing to do here. Commented May 12, 2015 at 17:23
  • I know, I forgot an rather important aspect of the question, apologies. Commented May 12, 2015 at 17:25

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm, perhaps my example wasn't that good, because there are multiple fields in the struct, not only the name, in that case, how would that be? sorry for the misunderstanding.
@Zetsuno I see now you've accepted mtijanic's offering. Good thing it helped.. though his solution is not C99 specific but C89 specific. The designated initializer I provided not only is C99 specific but also a better way of initialization (: Take this into a consideration.
2

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.

2 Comments

Thanks a lot, this did solve my problem, since it dosn't really matter if I initialize everything to zero, in my case.
player player_list[10] = {}; is using a GNU C extension. {0} is the ISO C way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.