簡體   English   中英

如何在C中獲取嵌套結構成員的偏移量?

[英]How to get the offset of a nested struct member in C?

info結構中打印checksum字段的偏移量的一種解決方案是使用宏typeofoffsetof

#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

我為什么要這樣做?

我有一個很大的結構,代表FLASH內存的內容,代表信息塊。 這些塊中的每一個都有一個我想檢查的校驗和:

if (s.info[0].checksum != checksum(s.info[0], offsetof(typeof(s.info[0]), checksum))) {
    printf("Oops\n");
}

由於typeof ,寫作不可移植。

我不知道你為什么要考慮(標准C中不存在) typeof是必需的。 如果你給struct一個標簽( information ),這與offsetof游泳:

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

typedef struct
{
    struct {
        int a;
    } something;

    struct information {
        int a;
        int b;
        int c[42];
        uint32_t checksum;
        int padding[10];
    } info[2];
    // ...
} S;

int main(void)
{
    printf("%zu\n", offsetof(S, info[0].checksum));
    printf("%zu\n", offsetof(S, info[1].checksum));
    printf("%zu\n", offsetof(struct information, checksum));
    printf("%zu\n", offsetof(S, info[0].checksum) - offsetof(S, info[0].a));
    return 0;
}

示例運行:

$ ./a.out
180
400
176
176

順便說一下不要為結構的typedef打擾。 他們沒用。 你不必相信我,但你可以相信Peter van der Linden。

使用指針算術。 獲取元素的地址,然后從結構的地址中減去該元素。

((unsigned char *) &(s.info[0]).checksum - (unsigned char *) &(s.info[0]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM