Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Structure offset

Tags:

c++

c

oop

I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.

IE: given

struct mstct {     int myfield;     int myfield2; }; 

I could write:

mstct thing; printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing)); 

And get offset 4 for the output. How can I do it without that mstct thing declaration/allocating one?

I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later.

like image 455
davenpcj Avatar asked Sep 26 '08 21:09

davenpcj


People also ask

What is offset of structure in C?

Description. The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.

How do you offset a struct?

Use offsetof() to find the offset from the start of z or from the start of x . #include <stddef. h> size_t offsetof(type, member); offsetof() returns the offset of the field member from the start of the structure type.


1 Answers

How about the standard offsetof() macro (in stddef.h)?

Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:

#define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field)) 
like image 84
Michael Burr Avatar answered Sep 19 '22 14:09

Michael Burr