0

I got a probably small problem using memcmp. I have two arrays (length = 3 byte) with exactly the same data.

If I try to compare them with memcmp, it fails?!

if (memcmp(ucbuffer, ucnewbuffer, buffer.sDeviceData.sLenght)) {
    cout << "val written, val ok!\n";
};

ucbuffer, ucnewbuffer are both unsigned char * and were allocated using

calloc(buffer.sDeviceData.sLenght, sizeof(unsigned char);

If i compare both arrays by hand, both it will result in being exactly the same.

Do you have any Idea?

Have a nice evening.

AllDayPiano
  • 414
  • 1
  • 4
  • 20

1 Answers1

9

That function returns zero (i.e., not true) when the buffers compare equal.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • I thought true = 0, false -1 so checking for 0 means true?! Hm... if you're right, than the rest of my code doesn't work either... – AllDayPiano Jun 14 '12 at 16:59
  • checking for 0 in this case means that the comparison is equal, 0 traditionally is false though – Dan F Jun 14 '12 at 17:08
  • *Any* C or C++ reference should tell you that false is zero and true is one (plus all other non-zero values). It's common for functions to return zero on *success*, and in that case, a non-zero result will sometimes indicate the error code. Maybe you were thinking of that and confused it with this situation. But `memcpy` has no failure result. Even if the buffers aren't equal, the function still *succeeds* in telling you the result. If it helps you remember, `memcpy` returns the same way as `strcpy`; the sign of the result tells you which argument should be sorted ahead of the other. – Rob Kennedy Jun 14 '12 at 17:09
  • Well yea, I come frome the Visual Basic corner were -1 is false, and >= 0 is true. That might have made me thinking, 0 is true. – AllDayPiano Jun 14 '12 at 17:58
  • Even in Visual Basic, False is zero. It's *True* that's -1. [cite](http://stackoverflow.com/q/4275800/33732) – Rob Kennedy Jun 14 '12 at 18:31
  • Oh well, damn, it's quite a long time ago I got in touch with programming. Astonishing how you mix up some things after a couple of years :) Thank you all guys. You really helped me. – AllDayPiano Jun 18 '12 at 04:46