我编写了以下 C 代码来比较两个内存区域并检查它们是否相同
#include <stdio.h>
struct s1 {
int a, b;
char c;
} s1;
int memcmpwannabe(void* value1, void *value2, int size1, int size2) {
if(size1 != size2)
return -1;
if(size1 == 0 || size2 == 0)
return -1;
//memcmp() wannabe
char *p1 = value1;
char *p2 = value2;
int sz = size1;
do {
if(*p1 != *p2)
break;
else
p1++, p2++;
}
while(--sz != 0);
if(sz == 0)
return 0;
return -1;
}
int main() {
struct s1 v1;
struct s1 v2;
v1.a = 1;
v1.b = 2;
v1.c = 'a';
v2.a = 1;
v2.b = 2;
v2.c = 'a';
int res = memcmpwannabe((void*) &v1, (void*) &v2, sizeof(s1), sizeof(s1));
printf("Res: %d\n", res);
}
结构是相同的,但无论如何都会返回-1。 经过一番调试后,我发现 char 变量后面有 3 个填充字节 充满了随机数据,而不是我所期望的零。
知道这一点以及我希望使其尽可能通用(因此使用 void* 作为参数)的事实,有人可以向我指出替代的字节到字节比较吗?
(在有人问之前,我正在编写一个自定义 memcmp() 因为在某些实现中 it will continue after a difference
最佳答案
Knowing this and the fact that i want to keep it as generic as possible (so using void* as arguments)
如果你只使用void *
指针,根据定义你对对象的内部组织一无所知。这意味着您对字节的含义一无所知(它们位于“真实”成员中,哪些位于隐藏的仅填充成员中)。
我想说这不是用标准 C 就能轻松做到的事情。
关于具有 char 成员的结构的自定义 memcmp(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28881341/