在 C 中使用 memcmp 比较结构的一部分

标签 c struct memcmp

<分区>

我有 2 个相同类型的结构,想比较它们。该结构的大小为 420 字节,我想在进行比较时跳过前 2 个字节,因为我知道它们永远不会匹配。我正在使用 memcmp 如下:

` typedef struct foo    // total of 420 bytes
{
  char c1,c2 ;
  int x ;
  struct temp y ;
  ...  // lot of other members
  ...
  ...
} ;
foo f1, f2 ;

memset (&f1, 0xff, sizeof(foo) ) ;
memset (&f2,0xff, sizeof(foo) ) ;

update_foo(&f1) ; // function which updates the structure by reading value from flash memory

// Now compare 2 structures starting with value x
if ( memcmp(&f1.x, &f2.x, sizeof(foo)-2 ) == 0 )
  // Do something
else
  // Do something else`

比较的结果给了我随机值。我假设当我传递“&f1.x”和“&f2.x”时,我跳过了前两个字节,比较的是剩余的 418 个字节。这个假设是否正确?

最佳答案

很难以可移植的方式做到这一点,不同平台上的 ABI 可能会将每个成员填充为单词 len,或者仅在某些情况下......所以如果我要写这个,我可能只会硬编码您感兴趣的比较...

C 不是一种非常动态的语言,如果你有兴趣动态地做这样的事情,你也许可以尝试像..

typedef struct
{
    int thatCanChange;
    int thatCanChange2;
    int thatICareAbout1;
    ...
    int lastThingICareAbout;
}a;

bool same( a * one, a * two)
{
    return memcmp(&(one->thatICareAbout1), &(two->thatICareAbout1), &(one->lastThingICareAbout) - &(one->thatICareAbout1) + sizeof(one->thatICareAbout1))==0;
}

关于在 C 中使用 memcmp 比较结构的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708591/

相关文章:

c - 如何从文本文件中读取数据并将其存储为结构?

c - 错误 : incomplete type is not allowed

c - 设置 UTF-8 语言环境后使用 fgetws?

c - 在 C 怪异行为中使用结构传递数组及其长度

c - 实现二叉搜索树 - "incompatible types when returning type ' struct item_t *'..."

c - memcmp 但需要将 block 与固定值进行比较

c - 结构填充和元素访问

c++ - C++ 中 sizeof(struct) 的奇怪输出

c - Memcpy func 获取指针变量?字符*p;字符* q; memcpy(p,q,10);会起作用吗?

c - 意外的 memcmp 返回值