Passing a NAME structure element to work in C?

Are there any simple ways to pass the name of a struct element to a function in C? For example, if I want this to 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>);
}
+4
source share
1 answer

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));
}
+6
source

Source: https://habr.com/ru/post/1656603/


All Articles