Alignment of internal members of structure in C language

Description:

******Different compilers and processors have different alignments for the internal members of the structure.

******Use the sizeof() operator to calculate the length of the structure.

### The offset of each member in the structure relative to the first address of the structure is an integer multiple of the member size. If necessary, the compiler will add padding between the members.

###The total size of the structure is an integer multiple of the size of the widest basic type member of the structure . If needed, the compiler will add a filler after the last member.

struct A
{
   
   
<span style="white-space:pre">	</span>unsigned short a;<span style="white-space:pre">	</span>//4bytes
	unsigned int b;<span style="white-space:pre">		</span>//4bytes
	unsigned char c;<span style="white-space:pre">	</span>//4bytes
}aa;
According to the structure member alignment, one byte of space should be allocated to c, but according to the alignment of the structure, 4 bytes are allocated to c. sizeof(aa)==12

The members of the structure are aligned, and storage space should be allocated according to the largest basic data type in the structure. For example: when a member A allocates more space than its own size, if the next member B needs space, A allocates the remaining space When the space is sufficient for storage B, then B will not be allocated, but if the storage for B cannot be satisfied, B will be allocated according to the largest data type of the structure.


###Calculate the offset of a member of the structure relative to the first address of the structure, which can be obtained through the macro offsetof().

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
//TYPE:结构体的类型
//MEMBER:结构体中某个成员
/*
 *offsetof(,)宏解析:
 *(TYPE  *)0:将0强制转换成指向结构体首地址的指针(结构体首地址为0地址)
 *((TYPE *)0)->MEMBER:结构体中某个变量
 * &((TYPE *)0)->MEMBER:取成员变量MEMBER(都是在0地址的基础上增加的)的地址
 * (size_t) &((TYPE *)0)->MEMBER:将取到的地址强制转换成size_t数据类型。
 */

Initialization of structure variables:

Structure:

struct A
{
	unsigned short b;
	unsigned int a;
	unsigned short c;
	unsigned short f;
	unsigned short g;
	unsigned short d;
	unsigned char e;
};

The first initialization method:

struct A aa={
	.b=2,
	.a=1,
	.c=3,
	.d=4,
	.e=5,
	.f=6,
	.g=7
	};	

The second initialization method:

struct A aa={1,2,3,4,5,6,7};

The third initialization method:

struct  A aa;
aa.b=2;
aa.a=1;
aa.c=3;
aa.d=4;
aa.e=5;
aa.f=6;
aa.g=7;





Guess you like

Origin blog.csdn.net/wzc18743083828/article/details/26584461