gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:28:44 25 4
gpt4 key购买 nike

假设我们有这样的结构:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com