0

Possible Duplicate:
How do you compare structs for equality in C?

I have a struct in C:

typedef struct Value
{
    int value1;
    int value2;
    int value3;
}myValue;

myValue valueA;
myValue valueB;

valueA.value1 = 1;
valueA.value2 = 2;
valueA.value3 = 3;

valueB.value1 = 1;
valueB.value2 = 2;
valueB.value3 = 3;

how to compare these valueA and valueB equals?

Community
  • 1
  • 1

2 Answers2

2

The only safe choice you have is to compare member by member.

You cannot use memcmp to compare the structure objects due to the paddings of unspecified value between the structure members.

And the equality operator == does not work with operands of a structure type.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • your wrong, in his example, all data types are the same within the struct, meaning that there would be no padding and he can memcmp just fine, and even if there are different data types, you can set the structure packing to 1, in VS and mingw it's #pragma pack(1) – Jordan LaPrise Apr 22 '14 at 15:55
  • @JordanLaPrise The fact that the members of the structure type are all of the same type is by no means a guarantee there will be non padding between members. C does not guarantee it and it's even not a safe assumption to do with existing implementations. – ouah Apr 22 '14 at 20:35
  • From my understanding of structs the reason padding would be implemented is due to the fact that the data types in the structure are of different lengths and thus adds padding to ensure that all of the elements are taking up equal space. – Jordan LaPrise Apr 22 '14 at 20:40
  • c++11 has a nice helper http://en.cppreference.com/w/cpp/types/is_pod to check if a memcmp is "valid" in the first place. memcmp is fine in certain contexts. – JeffCharter Sep 20 '17 at 23:41
1

You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs.

// bad
  memcmp(&struct1, &struct2, sizeof(struct1));

The above would fail for a struct like this:

typedef struct Foo {
  char a;
  /* padding */
  double d;
  /* padding */
  char e;
  /* padding */
  int f;
} Foo ;

You have to use member-wise comparison to be safe.

Afaq
  • 1,146
  • 1
  • 13
  • 25