memory allocation for structures elements

前端 未结 7 1183
故里飘歌
故里飘歌 2021-01-19 05:14

Hi I am having difficulties in understanding about how the memory is allocated to the structure elements.

For example if i have the below structure and the size of c

7条回答
  •  攒了一身酷
    2021-01-19 05:56

    If we create an array of such structure also the first element of the next array element can be place in 3392515188 (base + 36) as it is a multiple of 4, but why is it not happening this way?

    It can't because of the double elements in there.

    It's clear that the compiler and architecture you are using requires a double to be eight byte aligned. This is obvious because there is seven bytes of padding after the char c.

    This requirement also means that the entire struct must be eight byte aligned. There's no point in carefully making all the doubles aligned to eight bytes relative to the start of the struct if the struct itself is only four byte aligned. Hence the padding after the final int to make sizeof(temp) a multiple of eight.

    Note that this alignment requirement need not be a hard requirement. The compiler could choose to do the alignment even if doubles can be four byte aligned on the grounds that it might take more memory cycles to access the double if it's only four byte aligned.

提交回复
热议问题