[英]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.