Code

#include <stdio.h>

typedef struct {
    char a;
    int b;
    short c;
} MyStruct;

void print_offsets() {
    MyStruct my_struct;

    char *struct_baseaddr = (char *)&my_struct;
    size_t a_offset = (char *)&my_struct.a - struct_baseaddr;
    size_t b_offset = (char *)&my_struct.b- struct_baseaddr;
    size_t c_offset = (char *)&my_struct.c - struct_baseaddr;

    printf("Offset of a: %zu\n", a_offset);
    printf("Offset of b: %zu\n", b_offset);
    printf("Offset of c: %zu\n", c_offset);
    printf("Size: %zu\n", sizeof(my_struct));
 
}

int main() {
    print_offsets();
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

Expected Output

Offset of a: 0 Offset of b: 4 Offset of c: 8 Size: 12