是否有任何簡單的方法將結構成員的名稱傳遞給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>);
}
你可以使用成員[偏移](http://man7.org/linux/man-pages/man3/offsetof.3.html),而不是名稱。 – user2357112
概念上與http://stackoverflow.com/q/13653024/2564301相同,對吧? – usr2564301
您可以使用宏而不是函數。這對於一個更復雜的函數可能很快就會變得很奇怪,但爲了您的需要,您可以執行'#define example(x,member)printf(「%d \ n」,x.member)''。但這意味着你會失去類型安全(以及其他一些事情)。 – neoaggelos