Code

#include <stdio.h>

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

void print_offsets() {
    MyStruct s;
    //ép kiểu char để tính theo từng byte 
    //nếu ko ép kiểu thì sẽ lỗi vì phép tính con trỏ khác khiểu dữ liệu Struct/ int/ char/ short.
    int offset_a = (char*)(&s.a) - (char*)(&s);    
    int offset_b = (char*)(&s.b) - (char*)(&s);    
    int offset_c = (char*)(&s.c) - (char*)(&s);    
    int size = sizeof(s);
    printf("Offset of a: %d\n", offset_a);
    printf("Offset of b: %d\n", offset_b);
    printf("Offset of c: %d\n", offset_c);
    printf("Size: %d", size);
}

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