Search code examples
cintegercomparisonmemcmp

How the memcmp on structure with integer variable in c lang compares. Result is not as expected


I have a structure with integer, I am comparing the struct by using memcmp, I don't want to use other memthods.

   #include <stdio.h>
   #include <string.h>

   typedef struct Foo 
   {
      int d;
   } Foo;

   int main(int argc, const char * argv[])
   {
      Foo one, two;
      int result;
   
      memset(&one,0,sizeof(Foo));
      memset(&two,0,sizeof(Foo));
    
      one.d = 1022;
      two.d = 1024;
    
      result = memcmp((void*)&one, (void*)&two, sizeof(Foo));
      printf("comp with assignment %d\n",result);
    
      if (result == 0) printf("Arrays are the same\n");
    
      return 0;
   }

memcmpa should return -1, but it returns 1. why ? memcmp woth one.d = 1022 and two.d = 1023 will return correct value. why is so?


Solution

  • If you add two printfs in your code:

       typedef struct Foo 
       {
          int d;
       } Foo;
    
       int main(int argc, const char * argv[])
       {
          Foo one, two;
          int result;
       
          memset(&one,0,sizeof(Foo));
          memset(&two,0,sizeof(Foo));
        
          one.d = 1022;
          two.d = 1024;
    
          printf("%04x %04x\n", one.d, two.d);
        
          result = memcmp((void*)&one, (void*)&two, sizeof(one));
          printf("comp with assignment %d\n",result);
        
          if (result == 0) printf("Arrays are the same\n");
        
          return 0;
       }
    

    Result:

    03fe 0400
    comp with assignment 1
    

    You will see that the first byte of one is 0xfe and the first byte of two is 0x00 (they are in opposite order as most modern machines are little endioan) So 0xfe > 0x00 and memcmp returns 1