Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

c - Quickest way to initialize an array of structures to all-0's?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...