78. Struct Padding

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

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

void print_offsets() {
    MyStruct my_struct;

    char *struct_baseaddr = (char *)&my_struct;
    size_t a_offset = (char *)&my_struct.a - struct_baseaddr;
    size_t b_offset = (char *)&my_struct.b- struct_baseaddr;
    size_t c_offset = (char *)&my_struct.c - struct_baseaddr;

    printf("Offset of a: %zu\n", a_offset);
    printf("Offset of b: %zu\n", b_offset);
    printf("Offset of c: %zu\n", c_offset);
    printf("Size: %zu\n", sizeof(my_struct));
 
}

int main() {
    print_offsets();
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote