提问人:Geetha Anjali 提问时间:8/19/2022 最后编辑:tycoonGeetha Anjali 更新时间:8/20/2022 访问量:118
在 c lang 中具有整数变量的 memcmp on 结构如何比较。结果与预期不符
How the memcmp on structure with integer variable in c lang compares. Result is not as expected
问:
我有一个带有整数的结构,我正在使用 memcmp 比较结构,我不想使用其他 memthod。
#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 woth one.d = 1022 和 two.d = 1023 将返回正确的值。 为什么会这样?
答:
1赞
0___________
8/19/2022
#1
如果在代码中添加两个 s: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
你会看到 is 的第一个字节和 is 的第一个字节(它们的顺序相反,因为大多数现代机器都是小端的) So 和 返回one
0xfe
two
0x00
0xfe > 0x00
memcmp
1
0赞
Ted Lyngmo
8/19/2022
#2
它比较的是字节,而不是 s:int
memcmp
- 此函数读取对象表示,而不是对象值,并且通常仅对字节数组有意义:s 可能具有值不确定的填充字节,struct
看看一个如何看待字节级别,你会更清楚地看到它。它可以与最高有效字节一起存储 - 结果将取决于此。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;
}
可能的输出:
comparing these:
0 FE 00
1 03 04
2 00 00
3 00 00
comparing:
0 FE 00 => 254
.. and here it returned on the first byte compared (the least significant byte on my machine) and returned a positive value just like it did for you.
评论
int
int
little endian
big endian
0
-1
1
0