簡體   English   中英

結構上的 memcmp 與 c lang 中的 integer 變量的比較如何。 結果不如預期

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

我有一個 integer 的結構,我正在使用 memcmp 比較結構,我不想使用其他方法。

   #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 應該返回 -1,但它返回 1。為什么? memcmp one.d = 1022 和 two.d = 1023 將返回正確的值。 為什么會這樣?

如果在代碼中添加兩個printf

   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;
   }

結果:

03fe 0400
comp with assignment 1

您會看到一個字節的第one字節是0xfe ,而two字節的第一個字節是0x00 (它們的順序相反,因為大多數現代機器都是小字節序的)所以0xfe > 0x00並且memcmp返回1

它比較bytes ,而不是int s:

memcmp - This function reads object representations, not the object values, and is typically meaningful for byte arrays only: struct s may have padding bytes whose values are indeterminate,

看看一個int是如何看待字節級別的,你會看得更清楚。 它可以與最重要的字節首先最后存儲 - 並且memcmp的結果將取決於此。

為此,您可以創建自己的memcmp_debug

例子:

int memcmp_debug(const void *vpa, const void *vpb, size_t len) {
    const unsigned char *a = vpa, *b = vpb;

    puts("comparing these:");
    for(size_t i = 0; i < len; ++i) {
        printf("%2d %02X %02X\n", i, a[i], b[i]);
    }

    puts("\ncomparing:");
    for(unsigned i = 0; i < len; ++i) {
        int result = (int)a[i] - (int)b[i];
        printf("%2d %02X %02X  =>  %d\n", i, a[i], b[i], result);
        if(result) return result;
    }
    return 0;
}

可能的 output:

comparing these:
 0 FE 00
 1 03 04
 2 00 00
 3 00 00

comparing:
 0 FE 00  =>  254

..在這里它返回比較的第一個字節(我機器上的最低有效字節)並返回一個正值,就像它為你所做的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM