Struct Padding

Code

#include <stdio.h>

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

void print_offsets() {
  MyStruct offsetCheck;
  int a_offset = ((char*)&(offsetCheck.a) - (char*)&(offsetCheck));
  int b_offset = ((char*)&(offsetCheck.b) - (char*)&(offsetCheck));
  int c_offset = ((char*)&(offsetCheck.c) - (char*)&(offsetCheck));

  printf("Offset of a: %d\n", a_offset);
  printf("Offset of b: %d\n", b_offset);
  printf("Offset of c: %d\n", c_offset);

  int total_size = sizeof(offsetCheck);
  printf("Size: %d", total_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