# Thread: How do I compare structures??

1. ## How do I compare structures??

Ppl,
I am comparing two structures but C says that k>k2 and k==k2 are illegal for struct..how should I do it??
A

[code]
int cmp(KEY k, KEY k2)
{
int result;

if(k > k2)
{
result = 1;
}
else if(k == k2)
{
result = 0;
}
else
{
result = -1;
}

return result;
}
[\code]

2. 1. You can compare all the members of the structures separately.

2. You can create a function that would compare all the members of the structure, and return TRUE or FALSE.

3. As zeeshan said compare each member of the structure.

Code:
```/* Structure one greater than struct two */
int gt(struct name* one, struct name* two);

/* struct two equal to struct one */
int eq(struct name* one, struct  name* two);

/* etc..*/

struct name {
int a;
char b;
};

int main() {
struct name x,y;
x.a = 12;
y.a = 12;
x.b = 'x';
y.b = 'y';
if ( eq(&x, &y) ) {
printf("There Equal\n");
} else {
puts("Not Equal");
}
return 0;
}
int eq(struct name* one, struct  name* two) {
return (*one.a == *two.a && *one.b == *two.b);
}```
Hope this helps

kwigibo

4. If the two structures being compared are of the same type, use memcmp(), a single line comparison!

5. > use memcmp(), a single line comparison
Don't do this.

Structures can be padded, and the contents of padding bytes are undefined. memcmp doesn't know this and will blindly compare all bytes.

The only thing to do is compare each member