This C program will print the offsets from 0 in a C struct. There are numerous entries in the struct “foo” and this program prints all of the offsets easily.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stddef.h> #include <stdio.h> struct foo { char c; double d; double e; double f; double g; double h; double i; double j; }; int main() { printf("%zu %zu %zu %zu %zu %zu %zu %zu\n", \ offsetof(struct foo, c), offsetof(struct foo, d), \ offsetof(struct foo, e), offsetof(struct foo, f), \ offsetof(struct foo, g), offsetof(struct foo, h), \ offsetof(struct foo, i), offsetof(struct foo, j)); printf("Sizeof struct foo is: %li\n", sizeof(struct foo)); } |
Use the offsetof() function to get the offset of a struct item. e.g offsetof(struct foo, g);. And then this gets the size of the overall struct. This number grows of course as you add more items to the struct.
This is a very neat C trick to get information about a C struct. The offset values are in bytes. This is shown in the output below.
(base) ┌─jason-Lenovo-H50-55@jason⬎┓ ┗━━━━━┫└─◉ 5.1-~/Documents-08:37-⚫ ◉--[$] ☕ ./obs 0 8 16 24 32 40 48 56 Sizeof struct foo is: 64 |
Here is another example, this is using a rather obfuscated version of the offsetof() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> #include <stddef.h> #define OFFSET_OF_C (size_t)&(((struct foo *)0)->e) struct foo { char c; double d; double e; double f; double g; double h; double i; double j; }; int main() { printf("%zu\n", OFFSET_OF_C); printf("Sizeof struct foo is: %li\n", sizeof(struct foo)); } |
But, this still works very well.
(base) ┌─jason-Lenovo-H50-55@jason⬎┓ ┗━━━━━┫└─◉ 5.1-~/Documents-09:43-⚫ ◉--[$] ☕ ./obs 16 Sizeof struct foo is: 64 |