c语言结构体中整形数组初始化,c – 将{0,0}在结构体中初始化数组?

线

A C = {0,0};

8.5.1聚合[dcl.init.aggr] / 12

Braces can be elided in an initializer-list as follows. If the

initializer-list begins with a left brace,then the succeeding

comma-separated list of initializer-clauses initializes the members of

a subaggregate; it is erroneous for there to be more

initializer-clauses than members. If,however,the initializer-list

for a sub- aggregate does not begin with a left brace,then only

enough initializer-clauses from the list are taken to initialize the

members of the subaggregate; any remaining initializer-clauses are

left to initialize the next member of the aggregate of which the

current subaggregate is a member.

[Example:

06001

is a completely-braced initialization: 1,3,and 5 initialize the first row of the array y[0],namely y[0][0],

y[0][1],and y[0][2]. Likewise the next two lines initialize y[1] and

y[2]. The initializer ends early and therefore y[3]’s elements are

initialized as if explicitly initialized with an expression of the

form float(),that is,are initialized with 0.0. In the following

example,braces in the initializer-list are elided; however the

initializer-list has the same effect as the completely-braced

initializer-list of the above example,

06002

The initializer for y begins with a left brace,but the one for y[0] does not,therefore three elements

from the list are used. Likewise the next three are taken successively

for y[1] and y[2]. — end example ]

下一个

8.5.1聚合[dcl.init.aggr] / 7

If there are fewer initializer-clauses in the list than there are

members in the aggregate,then each member not explicitly initialized

shall be initialized from its brace-or-equal-initializer or,if there

is no brace-or-equal- initializer,from an empty initializer list.

在你的情况下,这意味着第一个0被分配给B [0],第二个0分配给B [1].然后根据8.5.1 / 7,其余的元素是值初始化的.

但是,为了清楚这种情况,您应该使用A C = {{0},0};或者更好

A C{}; // or A C = {};

唯一让我担心的是g警告(-Wextra):

warning: missing initializer for member ‘main()::A::D’

[-Wmissing-field-initializers] A C {0,0};

但是根据我对上述标准的解释,你应该是OK,D应该被初始化.我甚至测试了一些新的布局,结果是如预期的

#include

int main()

{

struct A { int B[100]; int D;};

A memory{};

memory.D = 42;

std::cout << memory.D << std::endl;

// let's place something an A at the location of memory

A* foo = new (&memory) A{0,0};

// line below outputs 0,so D is erased; not the case if A* foo = new (&memory) A;

std::cout << memory.D << std::endl; // outputs 0

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值