簡體   English   中英

我不知道如何在 c++ 中使用 memcmp

[英]I don't know how to use memcmp in c++

我想知道當我執行這個程序時為什么會出現這個結果

int arr[4][4] = { 0,0,1,1,
                  1,1,1,1,
                  0,1,1,0,      
                  1,1,1,1 
                } ;

int arr2[2][2] = {1};

cout << memcmp(arr, arr2, 4) << endl ;
cout << memcmp(arr+1, arr2, 4) << endl ;
cout << memcmp(arr+2, arr2, 4) << endl ;
cout << memcmp(arr+3, arr2, 4) << endl ;

結果是

-1
0
-1
0

怎么做comapre arr 和arr2 ?

我想知道為什么結果是 (-1 0 -1 0 )。

請。

memcmp的第三個參數應該是4*sizeof(int)

memcmp需要兩個void*並且不知道類型的寬度,它總是像指針是unsigned char*進行比較,所以你比較的是兩個指針指向的前 4 個字節(不是 4 個int

無論如何,如果你這樣做,你會在字節序上遇到一些問題。 我會建議使用一些考慮類型的比較函數。

memcmp 的語法是

 int memcmp ( const void * ptr1, const void * ptr2, size_t num );

它將 ptr1 指向的內存塊的前 num 個字節與 ptr2 指向的前 num 個字節進行比較,如果它們都匹配則返回零,或者與零不同的值表示如果它們不匹配則更大。

條件 1

如果在兩個內存塊中不匹配的第一個字節在 ptr1 中的值低於 ptr2 中的值,則 memcmp 的輸出將<0

條件 2

如果兩個內存塊的內容相等,則 memcmp 的輸出將為0 ,並且

條件 3

如果在兩個內存塊中不匹配的第一個字節在 ptr1 中的值大於 ptr2 中的值,則輸出將 >0

這是一個簡單的程序

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

     int main ()
     {
     char buffer1[] = "NEpAL";
     char buffer2[] = "NEPAL";

      int n;

     n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

     if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
     else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
     else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

      return 0;
      }

輸出將是

“尼泊爾”大於“尼泊爾”。

如 p = 112 和 P=80 。 希望能幫助到你

暫無
暫無

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

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