Code

#include <stdio.h>

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

void print_offsets() {

    MyStruct struc;
    int off;
    int off1;
    int off2;

    off = (int)((int *)(&struc.a) - (int *)(&struc));
    off1 = (int)((int *)(&struc.b) - (int *)(&struc));
    off2 = (int)((int *)(&struc.c) - (int *)(&struc));

    printf("Offset of a: %d\n",off*4);
    printf("Offset of b: %d\n",off1*4);
    printf("Offset of c: %d\n",off2*4);
    printf("Size: %d\n",(off+off1+off2)*4);
 
}

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