I suspect the answer could be different in C and C++ as well...
General question: what's the best (portable/compliant) way to do pointer-arithmetic to get the relative address of struct/class members without ever creating an instance of said class? I realize that, in some sense, this is outright wrong in C++, but I'll only be working with POD types.
Specific question: Is the following legal? (Can I partially dereference an invalid pointer, just for the sake of pointer arithmetic, without ever truly dereferencing the address?)
struct foobar {
int a;
double b;
};
// Can this operation be legally performed?
void* riskyPtr = &((foobar*)(0)->b);

5 comments:
There's a standard UNIX macro (offsetof(struct foobar, b)) in C that does that operation; I think it's usable from C++.
Wow, quick and right on the money. Thanks Jon!
I figured this had to be common/standard enough that there was a canonical solution.
I just can't stand to write functions of a type that require an instance for no good reason.
Also, looking in linux/stddef.h, I find the following:
(effing blogger doesn't allow <pre> tags in comments, bah.)
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
What does POD stand for here?
I automatically thought "proper orthogonal decomposition," which makes no sense at all in the present context.
When talking data structures, POD means "plain old data".
Post a Comment