C语言 -- 结构体字节对齐题目示例

结构体字节对齐题目示例

在做题之前先来看看:

以下题目都是在.c文件中运行。 常说熟能生巧,多做几道题,多分析分析~

struct s1
{
          
   
	char c1; //1 +3
	int i;  //4
	char c2; //1 + 3
};

struct s2
{
          
   
	char c1; //1
	char c2; //1 +2
	int i; //4
};

void main()
{
          
   
	printf("sizeof(s1) = %d
", sizeof(struct s1)); //12
	printf("sizeof(s2) = %d
", sizeof(struct s2));  //8
}
typedef struct Test
{
          
   
	short a; //2 +6
	struct
	{
          
   
		int b; //4 +4
		double c; //8
		long d; //4 +4
	};
	int e; //4 +4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //40
}
typedef struct Test
{
          
   
	char a; //1 +7
	double b; //8
	int c; //4 +4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //24
}
typedef struct Test
{
          
   
	char a; //1 +3
	int c; //4
	double b; //8
	
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //16
}
#pragma pack(2)//指定按两个字节对齐
typedef struct Test
{
          
   
	char a; //1 +1
	int c; //4
	double b; //8

}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //14
}
#pragma pack(2)//指定按两个字节对齐
typedef struct Test
{
          
   
	char a; //1
	char b; //1
	char c; //1

}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //3
}
typedef struct Test
{
          
   
	short a; //2 +6
	struct
	{
          
   
		int b; //4 +4
		double c; //8
		char d; //1 +7
	};
	int e; //4 +4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //40
}
typedef struct Test
{
          
   
	short a; //2 +6
	struct
	{
          
   
		int b; //4 +4
		double c[10]; //80
		char d; //1 +7
	};
	int e; //4 +4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //112
}
#pragma pack(2)//指定按两个字节对齐
typedef struct Test
{
          
   
	short a; //2
	struct
	{
          
   
		int b; //4
		double c; //8
		char d; //1 +1
	};
	int e; //4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); //20
}
//下面程序在.c中输出是32,.cpp中输出为8
typedef struct Test
{
          
   
	short a; //2 +6
	struct t   //原因是这个t,有名字之后就是个类型
	{
          
   
		double c; //8
		int b; //4
		char d; //1 +3
	};
	int e; //4 +4
}Test;

void main()
{
          
   
	printf("%d
", sizeof(Test)); 
}
#pragma pack(4)
typedef struct Test
{
          
   
	unsigned long a;
	unsigned short b[7];
	unsigned char c;

}Test;

void main()
{
          
   
	Test T, * pt;
	unsigned short* pu[10][10];
	printf("%d
", sizeof(pu)); //400
	printf("%d
", sizeof(T)); //20
	printf("%d
", sizeof(pt)); //4
	printf("%d
", sizeof(*pt)); //20
}
经验分享 程序员 微信小程序 职场和发展