简体   繁体   English

具有char成员的结构的自定义memcmp()

[英]Custom memcmp() of a struct with char member

I've written the following C code to compare two areas of memory and check if they are identical 我编写了以下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);

}

The structures are identical, but it will return -1 anyway. 结构相同,但是无论如何它将返回-1。 After some debugging i found that the 3 padding bytes after the char variable are filled with random data, not with zeroes as i was expecting. 经过一些调试后,我发现char变量后的3个填充字节填充了随机数据,而不是我期望的零。

Knowing this and the fact that i want to keep it as generic as possible (so using void* as arguments), can somebody point me to an alternative byte to byte comparison? 知道这一点以及我想保持其尽可能通用的事实(因此使用void *作为参数),有人可以指出我另一种字节对字节比较吗?

(Before somebody asks, i'm writing a custom memcmp() because in some implementations it will continue after a difference (在有人问之前,我正在编写一个自定义memcmp(),因为在某些实现中,它将在出现差异后继续

Knowing this and the fact that i want to keep it as generic as possible ( so using void* as arguments ) 知道这一点以及我想保持其尽可能通用的事实( 因此使用void *作为参数

If you only take void * pointers, by definition you know nothing about the internal organization of the objects. 如果仅采用void *指针,那么根据定义,您对对象的内部组织一无所知。 Which means you know nothing about the meaning of the bytes (which are in "real" members and which are in hidden, padding-only members). 这意味着您对字节的含义一无所知(这些字节在“真实”成员中,而在隐藏的仅填充成员中)。

I would say this is not something that you can easily do with standard C. 我要说的是,使用标准C可以轻松做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM