• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 319
  • Last Modified:

macro to find the byte offset of a struct member

Can someone please let me know how to write a macro that would find the byte
offset of a structure member...

Regards & Thanks,
arut
0
arut
Asked:
arut
  • 4
  • 3
  • 2
1 Solution
 
scrapdogCommented:
#define BYTEOFFSET(x,y) &(x.y)-&(x)

where x is the structure and y is the member

you may also need to define a macro for pointers to structures, such as

#define PBYTEOFFSET(x,y) &(x->y)-x
0
 
scrapdogCommented:
note that in both cases x would have to be a structure variable
0
 
KangaRooCommented:
There's a standard ANSI C macro for that:

#include <stddef.h>
size_t offsetof(struct_type, struct_member);
0
The Firewall Audit Checklist

Preparing for a firewall audit today is almost impossible.
AlgoSec, together with some of the largest global organizations and auditors, has created a checklist to follow when preparing for your firewall audit. Simplify risk mitigation while staying compliant all of the time!

 
KangaRooCommented:
#define      offsetof(TYPE, MEMBER)      ((size_t) &( ((TYPE *) 0)->MEMBER ))
0
 
arutAuthor Commented:
Dear ScrapDog,

                      Your solution does not seem to work.
                       error is : invalid operands to binary '-' operator.

                       Could you please provide a corrected code.

Regards & THanks,
arut


Dear Kangaroo,

                     Could you please explain what
                  ((Type *)0)->member is trying to do.

                 Why 0?




Regards & Thanks,
arut
0
 
scrapdogCommented:
d'oh!  sorry, I probably should have tested it...it looks like you need to typecast after all (as in KangaRoo's answer).

#define BYTEOFFSET(x,y) ((long int)&(x.y))-((long int)&(x))
0
 
arutAuthor Commented:
I'll try this one out!

Thank you,
arut
0
 
KangaRooCommented:
 ((TYPE*)0)
Cast NULL pointer to a pointer to TYPE (TYPE*)
  ((TYPE*)0)->MEMBER
Returns TYPE.MEMBER, next step takes the address of that member.
  &(((TYPE*)0)->MEMBER)
Returns the address of the MEMBER. Since 0 was used as the address for the TYPE object, this address is also the offset to the member.
Would be the similar to:
  TYPE tmp;
  size_t offset = &(tmp.MEMBER) - &tmp;
with &tmp == 0;
0
 
KangaRooCommented:
TW, this method does not require an object...
0

Featured Post

Will You Be GDPR Compliant by 5/28/2018?

GDPR? That's a regulation for the European Union. But, if you collect data from customers or employees within the EU, then you need to know about GDPR and make sure your organization is compliant by May 2018. Check out our preparation checklist to make sure you're on track today!

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now