c语言 指针 compare,使用memcmp()和指针算法比较C中的结构

我知道,由于未初始化的填充,memcmp()不能用于比较memset()未归零的结构.但是,在我的程序中,我有一个结构,在开始时有几个不同的类型,然后是几十个相同的类型,直到结构的结尾.我的想法是手动比较前几种类型,然后memcmp()在相同类型成员的剩余连续内存块上使用a .

我的问题是,C标准对结构填充有什么保证?我可以在任何或所有编译器上可靠地实现这一点吗?C标准是否允许在相同类型的成员之间插入struct padding?

我已经实现了我提出的解决方案,它似乎与预期完全一致gcc:

#include

#include

#include

struct foo

{

char a;

void *b;

int c;

int d;

int e;

int f;

};

static void create_struct(struct foo *p)

{

p->a = 'a';

p->b = NULL;

p->c = 1;

p->d = 2;

p->e = 3;

p->f = 4;

}

static int compare(struct foo *p1, struct foo *p2)

{

if (p1->a != p2->a)

return 1;

if (p1->b != p2->b)

return 1;

return

/* Note the typecasts to char * so we don't get a size in ints. */

memcmp(

/* A pointer to the start of the same type members. */

&(p1->c),

&(p2->c),

/* A pointer to the start of the last element to be compared. */

(char *)&(p2->f)

/* Plus its size to compare until the end of the last element. */

+sizeof(p2->f)

/* Minus the first element, so only c..f are compared. */

-(char *)&(p2->c)

) != 0;

}

int main(int argc, char **argv)

{

struct foo *p1, *p2;

int ret;

/* The loop is to ensure there isn't a fluke with uninitialized padding

* being the same.

*/

do

{

p1 = malloc(sizeof(struct foo));

p2 = malloc(sizeof(struct foo));

create_struct(p1);

create_struct(p2);

ret = compare(p1, p2);

free(p1);

free(p2);

if (ret)

puts("no match");

else

puts("match");

}

while (!ret);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值