【发布时间】:2017-03-17 09:17:06
【问题描述】:
在info 结构中打印checksum 字段的偏移量的一种解决方案是使用宏typeof 和offsetof:
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
typedef struct
{
struct {
int a;
} something;
struct {
int a;
int b;
int c[42];
uint32_t checksum;
int padding[10];
} info[2];
// ...
} S;
int main(void)
{
S s;
printf("%lu\n", offsetof(typeof(s.info[0]), checksum));
return 0;
}
不幸的是,typeof 不是标准的,所以我正在寻找一种更方便的方法来编写上面的示例,而不必在S 之外声明info。
我为什么要这样做?
我有一个代表信息块的闪存内容的大结构。这些块中的每一个都有一个我想检查的校验和:
if (s.info[0].checksum != checksum(s.info[0], offsetof(typeof(s.info[0]), checksum))) {
printf("Oops\n");
}
由于typeof,写作不可移植。
【问题讨论】:
-
出于兴趣,您这样做是为了解决什么问题?
-
@Bathsheba 查看我的更新了解更多详情
-
你总是可以给结构一个标签
-
offsetof返回size_t必须使用%zu打印出来