#include <stdio.h>
typedef struct {
short x,y;
char type;
} Tile;
int main(int argc, const char *argv[])
{
printf("%d\n",sizeof(short));
printf("%d\n",sizeof(char));
printf("%d\n",sizeof(Tile));
return 0;
}
The output is:
2
1
6
I expected sizeof(Tile) to be 5, instead of 6. Is this a well-defined behaviour that structs add one extra byte of memory usage, or is it implementation dependant?
It’s because of padding (kind of like rounding).
for example:
will likely differ in size, first will have size of 12B, second will likely only eat 8B (arch and compiler dependant).
Edit: gcc does padding by size of biggest memeber of struct.
Gcc can minimize this behavior by option -fpack-struct, however this may not be best idea ever, it could even backfire (network protocol implementantion is first thing that pops into my mind).