johan
johan

Reputation: 1983

char initialization in struct

I have the code below. I get the "warning: missing braces around initializer [-Wmissing-braces]" warning when I build it.

struct routing {
    int hop_distance;
    char timeinfo[13];
    char sender_ID[16];
    char gateway[16];
};

struct routing user_list[40]  =  { [0]={0,0,0,0}};

I guess I get the warning because of the char initialization, how should I initialize it?

struct routing user_list[40]  =  { [0]={0,{0},{0},{0}}};

or

struct routing user_list[40]  =  { [0]={0,'\0','\0','\0'}};

or some other way?

Upvotes: 1

Views: 220

Answers (2)

user405725
user405725

Reputation:

You have to surround arrays with curly braces:

struct routing user_list[40] = {
    [0] = { 0, { 0 }, { 0 }, { 0 } }
};

Upvotes: 0

Shahbaz
Shahbaz

Reputation: 47563

You are initializing element 0 of your array. Therefore:

 struct routing user_list[40] = { [0]={...} };

So far you got it right. In this element, you are initializing four members:

 struct routing user_list[40] = { [0]={..., ..., ..., ...} };

Also good.

Element 1 is an int, so you can initialize it with a number, such as 0.

Elements 2, 3 and 4 are arrays of char, so you can initialize them the same way you initialize arrays of char. {0}, {'\0'} or "" they all work:

 struct routing user_list[40] = { [0]={0, {0}, {'\0'}, ""} };

Note the above is an example showing you can use all three methods. In reality you take one method and use it in all three.

The reason you got a warning is because you are trying to initialize the arrays with a 0, instead of {0}.

Upvotes: 2

Related Questions