First off, you're casting the individual addresses to int
s. I don't think that's such a good idea. an int
is guaranteed to be at least 2 bytes or more in size, an address/pointer is generally 4 or 8 bytes. Casting these to int
just doesn't sit right. If I were to cast them to anything, I'd probably use unsigned long
for 32 bit systems, and unsigned long long
for 64 bit. I'd use the latter to be safe.
That said, I wouldn't cast the addresses at all, and just use the offsetof
macro.
Add #include <stddef.h>
to your file, and use the offsetof
macro, which casts the offset value to size_t
type, not an int
, mind you. It works simply by using 0 as the memory address of the struct, and then returns the address of the given member, giving the actual offset:
size_t offset = offsetoff(T1, c);
//struct, member
As Zack pointed out in his comment, the next part of the answer is somewhat irrelevant, but for the links it contains, and for completeness' sake, I'll just leave it here - as offsetof
is required of all implementations:
Define the macro yourself, if you don't have stddef.h for some reason (which it ought to, because offsetof
has been parto fo the standard for some time now: C89 and up), like so:
#ifndef offsetof
#define offsetof(s, m) ((size_t)&(((s *) 0)->m))
#endif
That ought to do the trick, but be wary: this implementation may cause undefined behaviour. How and why is explained here
I've taken the offsetof
definition above from the stddef.h source I found here, so you may just download that file, and use it, instead of defining the macro in your own file but keep in mind that the offsetof
you use is not 100% reliable.
Anyway, that's enough for now, more info on Google, but here's a couple of links: