一個解決方案打印在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
您可以隨時給結構一個標籤 –