How does sizeof calculate the size of structures

后端 未结 6 1888
有刺的猬
有刺的猬 2020-12-16 15:37

I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 short

6条回答
  •  庸人自扰
    2020-12-16 16:42

    This really puzzles me, why isn't alignment enforced for t

    What alignment do you want it to have ?

    Shorts can be aligned on 2 byte boundaries with no ill effects(assuming common x86 compilers all over here..). So if you create an array of struct ThreeeShorts , that struct having a size of 6 is fine, as any elements in such an array will start on a 2 byte boundary.

    Your struct IntAndChar contains an int, ints wants 4 byte alignment, so if you create an array of struct IntAndChar the size have to be 8 for the next element to be aligned on a 4 byte boundary.

    If we didn't consider arrays, it wouldn't matter much if struct IntAndChar were 5 bytes long, the compiler would just allocate it starting on a 4 byte boundary when you create one one the stack, or use it as a compound member in another struct.

    You can always get the number of elements in an array by doing sizeof(arrayofT)/sizeof(T), and array elements are guaranteed to be stored adjacently, such that the n'th element can be retreived by stepping N*sizeof(arrayelementtype) bytes from the start, and that's the main reason you'll see structs being padded at the end.

提交回复
热议问题