#include <stdio.h> #include <stdint.h> typedef struct { char a; int b; short c; } MyStruct; void print_offsets() { MyStruct s; uint8_t *p2s, *p2a, *p2b, *p2c; p2s = (uint8_t *) &s; p2a = (uint8_t *) &s.a; p2b= (uint8_t *) &s.b; p2c= (uint8_t *) &s.c; printf("Offset of a: %u\n", (p2a - p2s)); printf("Offset of b: %u\n", (p2b - p2s)); printf("Offset of c: %u\n", (p2c - p2s)); printf("Size: %u", sizeof(s)); } int main() { print_offsets(); return 0; }
get the addresses to all the structure elements in pointers to uint8_t
do pointer arithmetics
Test Cases
Test Results
Input
Expected Output
Offset of a: 0 Offset of b: 4 Offset of c: 8 Size: 12