0

I have a graph and one parameter to the graph is an equality function.

This is the code I've written:

bool equalityFunction(void *char1,void *char2)
{
    if(strncmp((char *)char1,(char *)char2, 20) == 0)
        return true;
    return false;
}

The function is supposed to take in struct-pointers and to check if these pointers point to structs that have charpointers that point on identical strings.

May be hard to understand or low information but can anyone think of how I could possible write the equalityFunction? Thanks.

Fjodor
  • 529
  • 1
  • 7
  • 19
  • 1
    Structure may fail to be examined in the memory image because there is that it includes the padding. – BLUEPIXY Aug 21 '14 at 10:35

2 Answers2

2

If the arguments to equalityFunction are structure pointers, you should treat them as such:

bool equalityFunction(void *struct1_, void *struct2_)
{
    struct someStruct *struct1 = struct1_;
    struct someStruct *struct2 = struct2_;
    if(strncmp(struct1->string, struct2->string, 20) == 0)
        return true;
    return false;
}

You don’t want to compare the structures themselves, but the strings they contain a pointer to.


And I’d advice you not to do unnecessary pointer casts. They don’t have any use, may hide bugs, and aren’t really nice to read.

Quentin
  • 62,093
  • 7
  • 131
  • 191
mafso
  • 5,433
  • 2
  • 19
  • 40
  • I tried using what you wrote but got the following error: dereferencing pointer to incomplete type. The struct I am using looks like this: typedef struct { bool aBool; char *aChar; } theStruct; – Fjodor Aug 21 '14 at 10:54
  • Then you should use your structure, I just picked some dummy name, because I didn't know yours… `theStruct *struct1 = struct1_;` etc. – mafso Aug 21 '14 at 10:59
  • Wait, did you write `struct theStruct *struct1 = struct1_;`? That's different from `theStruct *struct1 ...`. – mafso Aug 21 '14 at 11:02
  • Yeah, that's what I did... I managed to get it wrong somehow. I got it working now, thanks.(This message refers to your first comment here. And yeah, I wrote theStruct *struct1 = struct1_;) – Fjodor Aug 21 '14 at 11:03
0

If you want to compare pointers to structs, use pointers to structs as arguments, not void*:

bool equalityFunction(struct S* s1, struct S* s2)

Then the strncmp function is not good for comparing arbitrary structures, since it stops comparison at the first zero byte. The best way would be to compare the actual fields in the structures:

return s1->field1 == s2->field2 && ...

If any of the members on the structure cannot be compared with == (like e.g. another structure or a string) you need to use appropriate comparison, but the basic principle is - compare all fields which should be compared to check logical equality.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51