是什么结构{0}和memset 0之间的差 [英] what is the difference between struct {0} and memset 0

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

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1998752/which-one-to-use-memset-or-value-initialization-to-zero-out-a-struct\">Which一个使用 - memset的()或值初始化为零出一个结构


假设我们结构体是这样的:

 一个结构
{
    INT X;
    诠释Ÿ;
};

就是

之间的差

  A A = {0};

  A一;
memset的(安培A,0,sizeof的(A));


解决方案

无。最后的结果是,这两个初始化结构成员 0

C99标准6.7.8.21


  

如果有一个大括号括起来的列表更少的初始化值多于使用比在数组中的元素来初始化已知大小的数组元素或聚集的成员,或者更少的字符的字符串,则剩余合计应初始化隐含一样具有静态存储持续时间的对象。


您结构 A 是一个聚合并且上述规则适用于它。因此,所有的结构成员初始化值相同静态存储时间。这是 0

C99标准7.21.6.1的memset的功能:

 的void * memset的(无效* S,INT C,为size_t n)的;


  

该memset的功能复制的值c (转换为unsigned char型)到每首 N 对象的字符指向取值


在简单的话所有成员,包括你的结构的对象对齐/填充位 A 设置为 0

注意仅在C两种结构之间的区别就是 memset的设置对齐/填充到 0 为好,而集合初始化只能保证你的结构成员设置为 0

在这两种情况下,你不必通过约定的语言结构,因此无论你得到同样的效果访问对齐/填充字节。

Possible Duplicate:
Which one to use - memset() or value initialization to zero out a struct?

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.

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

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