传递结构成员NAME以在C中起作用? [英] Passing a struct member NAME to function in C?

查看:56
本文介绍了传递结构成员NAME以在C中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法可以将struct成员的名称传递给C语言中的函数?例如,如果我想做到这一点:

Is there any simple ways to pass the name of a struct member to a function in C? For example if I want to make this happen:

(我知道代码不正确,我只是写了它来解释问题)

(I know the code is incorrect, I just wrote it to explain the question)

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的非常接近的解决方案:

Not sure if this is exactly what you are looking for but here is a pretty close solution using 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));
}

这篇关于传递结构成员NAME以在C中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆