How do you compare structs for equality in C? How do you compare structs for equality in C? c c

How do you compare structs for equality in C?


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


You may be tempted to use memcmp(&a, &b, sizeof(struct foo)), but it may not work in all situations. The compiler may add alignment buffer space to a structure, and the values found at memory locations lying in the buffer space are not guaranteed to be any particular value.

But, if you use calloc or memset the full size of the structures before using them, you can do a shallow comparison with memcmp (if your structure contains pointers, it will match only if the address the pointers are pointing to are the same).


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