78. Struct Padding

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stddef.h>

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

void print_offsets() {
    MyStruct struct_padding;

    // int offset_a = 0;
    // int offset_b = sizeof(struct_padding.a);
    // if(offset_b < 4)
    // {
    //     offset_b = offset_a + 4;
    // }
    // int offset_c = sizeof(struct_padding.b);
    // if(offset_c < 4)
    // {
    //     offset_c = offset_c + 4;
    // }
    // offset_c = offset_a + offset_b + offset_c;

    int offset_a =  offsetof(MyStruct,a);
    int offset_b = offsetof(MyStruct,b);
    int offset_c = offsetof(MyStruct,c);

    // // int offset_a = &struct_padding.b - &struct_padding.a;
    // char *a_adress = &struct_padding.a;
    // int *b_adress = &struct_padding.b;

    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",sizeof(MyStruct));
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote