如何在C中获取嵌套结构成员的偏移量?

时间:2017-03-17 09:17:06

标签: c struct typeof offsetof

checksum结构中打印info字段的偏移量的一种解决方案是使用宏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不是标准的,所以我正在寻找一种更方便的方式来编写上面的示例,而不必在info之外声明S

为什么我要这样做?

我有一个很大的结构,表示代表信息块的FLASH内存的内容。每个块都有一个我想检查的校验和:

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

由于typeof,写作不可移植。

2 个答案:

答案 0 :(得分:3)

我不知道你为什么认为(标准C中不存在)CV_OCL_RUN是必需的。如果您为结构体提供标记(typeof):

,则可以使用offsetof
information

示例运行:

#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;
}

BTW,don't bother with typedefs for structs.他们没用。你不必相信我,但你可以相信Peter van der Linden。

答案 1 :(得分:0)

使用指针算术。获取元素的地址,然后从结构的地址中减去该元素。

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