#include <stdio.h>
#include <string.h>
int main()
{
int test1 = 8410092; // 0x8053EC
int test2 = 8404974; // 0x803FEE
char *t1 = ( char*) &test1;
char *t2 = (char*) &test2;
int ret2 = memcmp(t1,t2,4);
printf("%d",ret2);
}
Here's a very basic function that when run prints -2. Maybe I am totally misunderstanding memcmp, but I thought if it returns the difference between the first different bytes. Since test1 is a larger num than test2, shouldn't the printed value be positive?
I am using the standard gcc.7 compiler for ubuntu.
As pointed out in the comments,
memcmp()
runs byte comparison. Here is a man quoteIf the bytes are not the same, the sign of the difference depends on the target endianness.
One application of
memcmp()
is testing if two large arrays are the same, which could be faster than writing a loop that runs element by element comparison. Refer to this stack questions for more details. Why is memcmp so much faster than a for loop check?