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() {
    //To calculate offsets, I need to check the addresses of each char & calculate distance between them?
    //1. Create new instance of struct
    MyStruct padding;
    //printf("%p\n",&padding);
    //2. Create a struct pointer that points to first address of struct
    MyStruct *s_ptr = &padding;
    //printf("%p\n",s_ptr);
    //3. Create a char pointer that points to the address of the a char in padding struct
    char *a_ptr = &padding.a;
    //printf("%p\n",a_ptr);
    //4. Create an int pointer that points to the address of the int in the padding stuct
    int *b_ptr = &padding.b;
    //printf("%p\n",b_ptr);
    //5. Creat a short pointer that points to the address of the short in the padding struct
    short *c_ptr = &padding.c;
    //printf("%p\n",c_ptr);

    //6. Calculate offsets from the base address of the struct by subtracting hex addresses from one another
    //To calculate 1 byte ofset we need to cast both pointers as 1 byte pointers (chars)
    int offset_a = (char *)a_ptr - (char *)s_ptr;
    printf("Offset of a: %d\n",offset_a);

    int offset_b = (char*)b_ptr - (char*)s_ptr;
    printf("Offset of b: %d\n",offset_b);

    //Method 2: Using offsetof(Struct,Member)
    int offset_c = offsetof(MyStruct,c);
    printf("Offset of c: %d\n",offset_c);

    printf("Size: %d\n", sizeof(padding));
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote