How do you compare two instances of structs for equality in standard C?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
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
C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
@Greg is correct that one must write explicit comparison functions in the general case.
It is possible to use
memcmp
if:NaN
.-Wpadded
with clang to check this) OR the structs are explicitly initialized withmemset
at initialization.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?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.
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