How do you compare structs for equality in C?

2019-01-02 17:11发布

How do you compare two instances of structs for equality in standard C?

11条回答
人间绝色
2楼-- · 2019-01-02 18:08

If you do it a lot I would suggest writing a function that compares the two structures. That way, if you ever change the structure you only need to change the compare in one place.

As for how to do it.... You need to compare every element individually

查看更多
看风景的人
3楼-- · 2019-01-02 18:11

C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.

查看更多
浅入江南
4楼-- · 2019-01-02 18:11

@Greg is correct that one must write explicit comparison functions in the general case.

It is possible to use memcmp if:

  • the structs contain no floating-point fields that are possibly NaN.
  • the structs contain no padding (use -Wpadded with clang to check this) OR the structs are explicitly initialized with memset at initialization.
  • there are no member types (such as Windows BOOL) that have distinct but equivalent values.

Unless you are programming for embedded systems (or writing a library that might be used on them), I would not worry about some of the corner cases in the C standard. The near vs. far pointer distinction does not exist on any 32- or 64- bit device. No non-embedded system that I know of has multiple NULL pointers.

Another option is to auto-generate the equality functions. If you lay your struct definitions out in a simple way, it is possible to use simple text processing to handle simple struct definitions. You can use libclang for the general case – since it uses the same frontend as Clang, it handles all corner cases correctly (barring bugs).

I have not seen such a code generation library. However, it appears relatively simple.

However, it is also the case that such generated equality functions would often do the wrong thing at application level. For example, should two UNICODE_STRING structs in Windows be compared shallowly or deeply?

查看更多
余生请多指教
5楼-- · 2019-01-02 18:13

memcmp does not compare structure, memcmp compares the binary, and there is always garbage in the struct, therefore it always comes out False in comparison.

Compare element by element its safe and doesn't fail.

查看更多
爱死公子算了
6楼-- · 2019-01-02 18:15

Note you can use memcmp() on non static stuctures without worrying about padding, as long as you don't initialise all members (at once). This is defined by C90:

http://www.pixelbeat.org/programming/gcc/auto_init.html

查看更多
登录 后发表回答