c - struct {0} 和 memset 0 之间有什么区别

标签 c struct

假设我们有这样的结构:

struct A
{
    int x;
    int y;
};

有什么区别

A a = {0};

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

最佳答案

没有。最终结果是两者都将结构体成员初始化为0

C99 标准 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.

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

C99 标准 7.21.6.1 memset 函数:

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.

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

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

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

关于c - struct {0} 和 memset 0 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241705/

相关文章:

c - 无法在 c 中的二维数组中释放二维数组

c++ - C++ 中的结构填充

c - c 中多线程的错误输出?

javascript - 转到 : format struct for javascript (json without keys)

c - 从结构数组中的前一个结构获取变量值

c# - Java 和 C# 中 "primitive"、 "value type"、 "struct"、 "class"、 "wrap"的定义

c++ - dlopen 或 dlclose 未调用信号处理程序

c - "."作为结构中变量名的开始

c++ - 有人解释汇编语言级别的左值和右值吗?

c - 在父进程中运行单独的进程