簡體   English   中英

如何在結構上使用 offsetof()?

[英]How do you use offsetof() on a struct?

我想要mystruct1中的 param 行的 offsetof() 。 我試過了

offsetof(struct mystruct1, rec.structPtr1.u_line.line) 

並且

offsetof(struct mystruct1, line)  

但兩者都不起作用。

union {
    struct mystruct1 structPtr1;
    struct mystruct2 structPtr2;
} rec;

typedef struct mystruct1 {
    union {
        struct {
            short len;
            char buf[2];
        } line;

        struct {
            short len;
        } logo;

    } u_line;
};

offsetof()宏有兩個參數。 C99 標准說(在 §7.17 <stddef.h>中):

 offsetof(type, member-designator)

它擴展為具有size_t類型的整數常量表達式,其值是以字節為單位的偏移量,從其結構的開頭(由 type 指定)到結構成員(由 member-designator 指定)。 類型和成員代號應使給定的

static type t;

然后表達式&(t.member-designator)計算為地址常量。

所以,你需要寫:

offsetof(struct mystruct1, u_line.line);

但是,我們可以觀察到答案將為零,因為mystruct1包含一個union作為第一個成員(也是唯一的),並且它的line部分是聯合的一個元素,因此它將位於偏移量 0 處。

您的struct mystruct1有 1 個名為u_line的成員。 您可以看到該成員的偏移量

offsetof(struct mystruct1, u_line); // should be 0

或者如果您指定每個“父母身份級別”,則為下線成員

offsetof(struct mystruct1, u_line.line);
offsetof(struct mystruct1, u_line.line.buf);
offsetof(struct mystruct1, u_line.logo);

一篇關於這方面的好文章是:

使用 offsetof() 宏學習新技巧

我在嵌入式代碼中經常使用 offsetof 宏,以及文章中討論的修改后的 SIZEOF 宏。

首先,AFAIK, offsetof旨在僅與結構的直接成員一起使用(我對此是否正確?)。

其次,了解流行的offsetof實現的內部細節,我可以建議嘗試

offsetof(struct mystruct1, u_line.line) 

這應該有效。 它是否符合標准對我來說是一個懸而未決的問題。

PS 從@Jonathan Leffler 的回答來看,這應該確實有效。

暫無
暫無

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

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