Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Position Of Field In Struct

Tags:

c

struct

A fairly simple question (I hope). Given a struct in C (the layout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named field in the struct?

Support for unions would be a bonus. The compiler is VC++ 2008. Assume that #pragma pack(1) is used.

Cheers

like image 981
Alistair Evans Avatar asked Dec 28 '22 05:12

Alistair Evans


1 Answers

You're looking for offsetof. It should be in stddef.h, but in case you don't have that, a sample implementation (from wikipedia):

#define offsetof(st, m) \
    ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))

For a union, the offset of every field is 0.

like image 125
Carl Norum Avatar answered Jan 10 '23 07:01

Carl Norum