why padding is not happening in this case?

前端 未结 4 1647
半阙折子戏
半阙折子戏 2020-12-23 15:14

As per my knowledge, By default 4-byte alignment will be done. say

typedef struct
{
     int data7;  
     unsigned char data8;
     //3 -bytes will be added         


        
相关标签:
4条回答
  • 2020-12-23 15:39

    data7 is a 4-byte item, so the compiler will normally attempt to align it to an address that's a multiple of 4.

    data1 is a one-byte item, so the compiler won't try to align it to any particular boundary (i.e., there would be no real gain from doing so).

    0 讨论(0)
  • 2020-12-23 15:42

    None of the fields in your second struct require 4-byte alignment. unsigned char only needs 1-byte alignment. Therefore, there is no need to actually align it to 4 bytes.

    Structs are generally only aligned to the maximum alignment of all the fields.

    0 讨论(0)
  • 2020-12-23 15:50

    Char requires 1 byte alignment. The max data type there is char , which is one byte alignment hence you are getting the size as '6'.

    You can check this site for more understanding. http://www.geeksforgeeks.org/archives/9705. They have explained it in detail.

    0 讨论(0)
  • 2020-12-23 15:57

    No, in a typical implementation Sample2 is not a 4-bute aligned structure. It is a 1-byte aligned structure.

    In a typical implementation, the alignment requirement of the whole structure is calculated as the maximum of the alignment requirement of its individual members. This is why your Sample1 has alignment requirement of int (4 on your platform), and your Sample2 has alignment requirement of unsigned char, which is 1.

    0 讨论(0)
提交回复
热议问题