Struct Padding

Code

#include <stdio.h>

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

void print_offsets() {
    MyStruct m;
    int offset;
    int size;
    char*p1 = (char*)&m;;
    char*p2 = (char*)&m.a;
    offset = (p2 - p1);
    printf("Offset of a: %d\n", offset);
    p2 = (char*)&m.b;
    offset = p2-p1;
    printf("Offset of b: %d\n", offset);
    p2 = (char*)&m.c;
    offset = p2-p1;
    printf("Offset of c: %d\n", offset);
    size = sizeof(m);
    printf("Size: %d\n", 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