struct {0} 和 memset 0 有什么区别 [英] what is the difference between struct {0} and memset 0

查看:24
本文介绍了struct {0} 和 memset 0 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这样的结构:

结构体A{整数 x;输入 y;};

有什么区别

A a = {0};

A a;memset(&a,0,sizeof(A));

解决方案

无.最终结果是两者都将结构成员初始化为 0.

C99 标准 6.7.8.21

<块引用>

如果花括号括起来的列表中的初始值设定项少于集合的元素或成员数,或者用于初始化已知大小数组的字符串文字中的字符少于数组中的元素数,则剩余的聚合应与具有静态存储持续时间的对象一样隐式初始化.

您的结构 A 是一个集合,上面的规则适用于它.因此,所有结构成员都使用与静态存储持续时间相同的值进行初始化.哪个是 0.

C99 Standard 7.21.6.1 memset 函数:

void *memset(void *s, int c, size_t n);

<块引用>

memset 函数将 c 的值(转换为无符号字符)复制到 s<指向的对象的前 n 个字符中的每一个/代码>.

简单地说,所有成员,包括结构对象中的对齐/填充位A都设置为0.

请注意,C 中两种构造之间的唯一区别在于 memset 也将对齐/填充设置为 0,而聚合初始化仅保证您的结构成员设置为 0.

在任何一种情况下,您都无法通过约定语言结构访问对齐/填充字节,因此两者都能获得相同的效果.

Assume we have struct like this:

struct A
{
    int x;
    int y;
};

what is the difference between

A a = {0};

and

A a;
memset(&a,0,sizeof(A));

解决方案

None. The final outcome is that both initialize structure members to 0.

C99 Standard 6.7.8.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Your structure A is an aggregate and above rule applies to it. So all the structure members are initialized with value same as for static storage duration. Which is 0.

C99 Standard 7.21.6.1 The memset function:

void *memset(void *s, int c, size_t n);

The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.

In simple words all the members including the alignment/padding bits in object of your structure A are set to 0.

Note that only difference between the two constructs in C is that memset sets the alignment/padding to 0 as well, while the aggregate initialization only guarantees that your structure members are set to 0.

In either case you do not have access to the alignment/padding bytes through convention language constructs and hence both get you the same effect.

这篇关于struct {0} 和 memset 0 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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