簡體   English   中英

將結構成員NAME傳遞給C中的函數?

[英]Passing a struct member NAME to function in C?

有沒有簡單的方法將結構成員的名稱傳遞給C中的函數? 例如,如果我想要實現這一點:

(我知道代碼不正確,我只是寫它來解釋這個問題)

struct Test
{
    int x;
    int y;
};

int main()
{
    struct Test t;
    t.x = 5;
    t.y = 10;

    example(t, <MEMBER NAME>);
}

void example(struct Test t, <MEMBER NAME>)
{
    printf("%d", t.<MEMBER NAME>);
}

不確定這是否正是您正在尋找的,但這是一個使用offsetof非常接近的解決方案:

struct Test
{
    int x;
    int y;
};

void example(void *base, size_t offset)
{
    int *adr;
    adr = (int*)((char*)base + offset);
    printf("%d\n", *adr);
}

int main(int argc, char **argv)
{
    struct Test t;

    t.x = 5;
    t.y = 10;

    example(&t, offsetof(struct Test, y));
}

暫無
暫無

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

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