Quickest way to initialize an array of structures

2019-01-22 18:35发布

问题:

I'm trying to initialize an array of structures to all-0's, using the below syntax:

STRUCTA array[MAX] = {0};

However, I'm getting the following warning from gcc :

warning: missing braces around initializer

What am i doing wrong - is there another/better way to do this ?

回答1:

It the first member of your struct has a scalar type, use

STRUCTA array[MAX] = {{ 0 }};

If the first member of your struct happens to be another struct object, whose first member has scalar type, then you'll have to use

STRUCTA array[MAX] = {{{ 0 }}};

and so on. Basically, you have to open a new level of nested {} every time you "enter" another nested aggregate (a struct or an array). So in this case as long as the first member of each nested aggregate is also an aggregate, you need to go deeper with {}.

All these extra braces are only there to avoid the warning. Of course, this is just a harmless warning (in this specific case). You can use a simple { 0 } and it will work.

Probably the the best way to deal with this is to disable this warning entirely (see @pmg's answer for the right command-line option). Someone working on GCC wasn't thinking clearly. I mean, I understand the value of that warning (and it can indeed be very useful), but breaking the functionality of { 0 } is unacceptable. { 0 } should have been given special treatment.



回答2:

gcc is being a nuisance. It should accept that without warnings.
Try this

STRUCTA array[MAX] = {{0}};

That gcc behaviour can be controlled with the option -Wmissing-braces or -Wno-missing-braces.

-Wall enables this warning; to have -Wall but not the missing braces, use -Wall -Wno-missing-braces



回答3:

This is merely a harmful warning issued by gcc, and I would disable it with -Wno-braces. {0} is an extremely useful "universal zero initializer" for types whose definition your code is not supposed to be aware of, and gcc's discouraging its use is actively harmful to the pursuit of good code.

If gcc wants to keep this warning, it should at least special-case {0} and disable the warning in this one case.



回答4:

Arrays are initialized with braces, but so are structs. You probably need to put an extra set of braces around your 0 and, depending on how STRUCTA is defined, some extra 0s separated by commas.



回答5:

It depends on the STRUCTA. For example :

typedef struct structa 
{
    int a, b;
} STRUCTA;

int main (int argc, char const* argv[])
{
    STRUCTA array[10] = {{0,0}};
    return 0;
}


回答6:

Can STRUCTA be assigned to 0?

You can always use memset(), too.