Code

#include <stdio.h>
#include <stdint.h>
typedef struct {
    char a;
    int b;
    short c;
} MyStruct;

void print_offsets(MyStruct *ptr) {

    int a_offset = (uint8_t *)(&(ptr->a)) - (uint8_t *)ptr;
    printf("Offset of a: %d\n", a_offset);
    int b_offset = (uint8_t *)(&(ptr->b)) - (uint8_t *)ptr;
    printf("Offset of b: %d\n", b_offset);
    int c_offset = (uint8_t *)(&(ptr->c)) - (uint8_t *)ptr;
    printf("Offset of c: %d\n", c_offset);
    printf("Size: %d\n", sizeof(MyStruct));
}

int main() {
    MyStruct x;
    print_offsets(&x);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

Expected Output

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