0

This is my code

#include <stdio.h>
#include <stdint.h>
#if UINTPTR_MAX == 0xffffffff
#define SIZE 32
#elif UINTPTR_MAX == 0xffffffffffffffff
#define SIZE 64
#else
#define SIZE 69
#endif

struct Goku{
    int x,y;
    char b,c;
};

int main(){
    printf("Word size : %d bytes\n",SIZE/8);
    printf("Struct size : %lu bytes\n",sizeof(struct Goku));
    printf("Integer size : %lu bytes\n",sizeof(int));
    printf("Char size : %lu bytes\n",sizeof(char));
    return 0;
}

This the output

Word size : 8 bytes
Struct size : 12 bytes
Integer size : 4 bytes
Char size : 1 bytes

This is what I expected

Word size : 8 bytes
Struct size : 16 bytes
Integer size : 4 bytes
Char size : 1 bytes

I expected the structure to be 16-bytes long but it turns out to be 12-bytes

enter image description here

What am I doing wrong here?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Saptarshi Dey
  • 125
  • 1
  • 7
  • 4
    Your expectation is wrong. Since `sizeof(int) == 4`, the size of the structure needs to be a multiple of 4 to maintain 4-byte alignment, not a multiple of 8. – Jonathan Leffler Aug 04 '23 at 15:39
  • 3
    structs are padded to their alignment. The alignment of a struct is the largest alignment of any of its members. The largest alignment is that of int. Int has 4 byte alignment – Homer512 Aug 04 '23 at 15:39
  • 2
    The only thing that's being done wrong here is expecting specific padding from a compiler. Just because the hardware platform supports a largest int value of 64 bits does not mean that its optimal memory alignment would also be 64 bit, for various datatypes. hardware is far more complex, these days. – Sam Varshavchik Aug 04 '23 at 15:40
  • @Homer512 what if we use a structure inside another structure. How will the padding be calculated then? – Saptarshi Dey Aug 04 '23 at 16:06
  • 2
    Since the largest alignment of the elements determines the alignment of the containing structure, you can recursively determine the alignment up to the outmost structure. – the busybee Aug 04 '23 at 17:02

0 Answers0