将结构数组初始化为全 0 的最快方法? [英] Quickest way to initialize an array of structures to all-0's?

查看:22
本文介绍了将结构数组初始化为全 0 的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下语法将结构数组初始化为全 0:

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

STRUCTA array[MAX] = {0};

但是,我从 gcc 收到以下警告:

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 ?

推荐答案

如果结构的第一个成员是标量类型,请使用

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 }}};

等等.基本上,每次输入"另一个嵌套聚合(结构或数组)时,都必须打开一个新级别的嵌套 {}.所以在这种情况下,只要每个嵌套聚合的 first 成员也是一个聚合,就需要深入了解 {}.

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 {}.

所有这些额外的大括号只是为了避免警告.当然,这只是一个无害的警告(在这种特定情况下).您可以使用一个简单的 { 0 } 并且它会起作用.

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.

处理此问题的最佳方法可能是完全禁用此警告(有关正确的命令行选项,请参阅@pmg 的答案).从事 GCC 工作的人并没有想清楚.我的意思是,我理解该警告的价值(它确实非常有用),但破坏 { 0 } 的功能是不可接受的.{ 0 } 应该得到特殊处理.

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.

这篇关于将结构数组初始化为全 0 的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆