Get field position in structure

Pretty simple question (hopefully). Given the structure in C (whose layout is known at compile time), is there a way (through a macro or another) so that I can access the byte position of the named field in the structure?

Union support will be a bonus. The compiler is VC ++ 2008. Suppose that it is used #pragma pack(1).

Greetings

+3
source share
2 answers

You are looking for offsetof. It should be in stddef.h, but in case you do not have it, an approximate implementation (from wikipedia ):

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

To combine the offset of each field 0.

+6
source

Use offsetof, from <stddef.h>.

( MSV++ 2008 , Carl Norum. , C89, ).

+3

Source: https://habr.com/ru/post/1773667/


All Articles