From there I know that it is illegal in C
to call offsetof
on a pointer, but why is it undefined behaviour? Standard implementation
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
seems suitable even for pointer MEMBER
, I can't get why it doesn't work.
Example on the architecture where int
is 4 bytes:
#include <stddef.h>
#include <stdio.h>
struct foo {
int a;
int *ptr;
};
int main() {
printf("Offset of ptr: %zu\n", offsetof(struct foo, ptr));
return 0;
}
That code will return 8, whereas if ptr
was just int
, it would return 4. But in both cases that member is on the same offset of 4.
Edit: I did wrong assumption and the mentioned link is invalid. The problem lied in structure padding, as was explained
The comment you link to is for C++ and not C. It does not apply to C.
Further, it does not say offsetof
cannot be used on (not “called”; it is not a function) a pointer member (that is, a member of the structure that is a pointer). It says offsetof
cannot be used on a member pointer.
A member pointer is a C++ thing that does not exist in C. It is a special kind of pointer that refers to a member within a class context. (It is not a stand-alone pointer that can be used by itself.)
So the reason you cannot use offsetof
on a member pointer in C is that no such thing exists in C.