U
Urs Thuermann
With offsetof() I can get the offset of a member in a struct. AFAICS,
it is portable and clean to use this offset to access that member. I
need to do something like this
struct foo {
struct foo *next;
int a;
int b;
int c;
};
void iterate(struct foo *list, size_t off)
{
struct foo *p;
for (p = list; p; p = p->next) {
int i = *(int *)((char *)p + off); /* [1] */
/* do something with i */
}
}
void func(struct foo *f)
{
iterate(f, offsetof(struct foo, a);
iterate(f, offsetof(struct foo, b);
iterate(f, offsetof(struct foo, c);
}
[1] Is this code portable and without undefined or implementation-defined
behavior?
Or is there a better way to achieve the same?
urs
it is portable and clean to use this offset to access that member. I
need to do something like this
struct foo {
struct foo *next;
int a;
int b;
int c;
};
void iterate(struct foo *list, size_t off)
{
struct foo *p;
for (p = list; p; p = p->next) {
int i = *(int *)((char *)p + off); /* [1] */
/* do something with i */
}
}
void func(struct foo *f)
{
iterate(f, offsetof(struct foo, a);
iterate(f, offsetof(struct foo, b);
iterate(f, offsetof(struct foo, c);
}
[1] Is this code portable and without undefined or implementation-defined
behavior?
Or is there a better way to achieve the same?
urs