-2

If I send memcmp two pointers to integers, then it seems to interpret the integers as chars.

For example:

int a = 5;
int b = 256;
int res = memcmp(&a,&b,sizeof(int));

In the code above, it returns 1.

I'd like to get a better understanding of this function, and I am wondering if I'm either using it wrong or if there is a similar function for comparing blocks of memory holding int values.

barak manos
  • 29,648
  • 10
  • 62
  • 114

3 Answers3

5

Suppose that the size of an int is 4 bytes (which is mostly, though not always, the case):

  • On a little-endian processor, you have:
    • int a = 5; // Lowest address to highest address 0x05 0x00 0x00 0x00
    • int b = 256; // Lowest address to highest address 0x00 0x01 0x00 0x00
  • On a big-endian processor, you have:
    • int a = 5; // Lowest address to highest address 0x00 0x00 0x00 0x05
    • int b = 256; // Lowest address to highest address 0x00 0x00 0x01 0x00

Now, function memcmp compares each pair of bytes sequentially:

  • If the byte of the first operand is larger than the byte of the second operand, then it return +1
  • If the byte of the first operand is smaller than the byte of the second operand, then it return -1
  • If it completes the comparison without encountering any such pair of bytes, then it returns 0

As you can see:

  • On a little-endian processor, it will return +1 after comparing the first pair of bytes (0x05 > 0x00)
  • On a big-endian processor, it will return -1 after comparing the third pair of bytes (0x00 < 0x01)
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • The idea is correct, but the result is not always exactly "+1" or "-1". Just its signal should be used (that is '[...] then it returns a positive number', '[...] then it returns a negative number'). – rslemos Jul 21 '14 at 18:28
  • @rslemos - Can you describe more on your comment? something missed? I can see only ' [...] ' is this a copy paste error? – tmz Dec 31 '21 at 11:35
2

memcmp will compare bytes (aka char). To know whether an int of x bytes will be bigger or smaller than the other you will need to know the endianess of its representation.

Why not just compare the ints directly?

*a > *b
*a < *b
*a == *b
*a != *b
rslemos
  • 2,454
  • 22
  • 32
0

You must be using a system that stores integers in memory in little-endian format (i.e. 5 is 05 00 00 00 and 256 is 00 01 00 00). When you memcmp these values, the first byte of the first value is greater than the first byte of the second value, so the return value is greater than 0.

nobody
  • 19,814
  • 17
  • 56
  • 77