简体   繁体   English

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

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

One solution to print the offset of the checksum field in the info struct, is to use the macros typeof and offsetof : 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;
}

Unfortunately, typeof is not standard, so I am looking for a more convenient way to write the above example without having to declare info outside from S . 不幸的是, typeof不是标准的,所以我正在寻找一种更方便的方式来编写上面的例子,而不必在S之外声明info

Why I am trying to do this? 我为什么要这样做?

I have a big structure that represent the content of a FLASH memory that represent blocks of information. 我有一个很大的结构,代表FLASH内存的内容,代表信息块。 Each of these blocks have a checksum that I would like to check: 这些块中的每一个都有一个我想检查的校验和:

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

The writing is not portable because of typeof . 由于typeof ,写作不可移植。

I don't know why you are thinking a (non-existing in Standard C) typeof is required. 我不知道你为什么要考虑(标准C中不存在) typeof是必需的。 This goes swimmingly with offsetof if you give the struct a tag ( information ): 如果你给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;
}

Example run: 示例运行:

$ ./a.out
180
400
176
176

BTW, don't bother with typedefs for structs. 顺便说一下不要为结构的typedef打扰。 They are useless. 他们没用。 You don't have to believe me, but you can believe Peter van der Linden. 你不必相信我,但你可以相信Peter van der Linden。

Use pointer arithmetic. 使用指针算术。 Get the address of the element, and then subtract that from the address of the structure. 获取元素的地址,然后从结构的地址中减去该元素。

((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