一个解决方案打印在info
结构的偏移checksum
场的,是使用宏typeof
和offsetof
:如何在C中获取嵌套结构成员的偏移量?
#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
@Bathsheba查看我的更新了解更多详情 – nowox
您可以随时给结构一个标签 –