gpt4 book ai didi

c - C结构的内部一致性

转载 作者:太空狗 更新时间:2023-10-29 16:43:15 25 4
gpt4 key购买 nike

如果我有两个初始化为具有相同成员的 C 结构,我可以保证:

memcmp(&struct1, &struct2, sizeof(my_struct))

总是返回零吗?

最佳答案

我认为您不能安全地memcmp 结构来测试是否相等。

来自 C11 §6.2.6.6 类型的表示

When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values.

这意味着您需要编写一个函数来比较结构的各个元素

int my_struct_equals(my_struct* s1, my_struct* s2)
{
if (s1->intval == s2->intval &&
strcmp(s1->strval, s2->strval) == 0 &&
s1->binlen == s2->binlen &&
memcmp(s1->binval, s2->binval, s1->binlen) == 0 &&
...
) {
return 1;
}
return 0;
}

关于c - C结构的内部一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16815611/

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