Friday, July 20, 2007

C/C++ Question

I'll ask here first... I think this is legal, I can test that it works, but I want to know if it's supposed to be legal (ie if it counts as "portable" to any extent).

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:

jwadams said...

There's a standard UNIX macro (offsetof(struct foobar, b)) in C that does that operation; I think it's usable from C++.

Lemming said...

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.

Lemming said...

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)

Mason said...

What does POD stand for here?

I automatically thought "proper orthogonal decomposition," which makes no sense at all in the present context.

Lemming said...

When talking data structures, POD means "plain old data".