Code

#include <stdio.h>
#include <stdint.h>

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

void print_offsets() {
    MyStruct s;

    size_t off_a = (size_t)((unsigned char*)&s.a - (unsigned char*)&s);
    size_t off_b = (size_t)((unsigned char*)&s.b - (unsigned char*)&s);
    size_t off_c = (size_t)((unsigned char*)&s.c - (unsigned char*)&s);

    printf("Offset of a: %zu\n", off_a);
    printf("Offset of b: %zu\n", off_b);
    printf("Offset of c: %zu\n", off_c);
    printf("Size: %zu\n", sizeof(MyStruct));
}

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