½á¹¹ÌåµÄ´óС²»ÊǽṹÌåÔªËص¥´¿Ïà¼Ó¾ÍÐеģ¬ÒòΪÎÒÃÇÖ÷Á÷µÄ¼ÆËã»úʹÓõĶ¼ÊÇ32bit×Ö³¤µÄ»òÕß64bit×Ö³¤µÄCPU£¬¶ÔÕâÀàÐ͵ÄCPUÈ¡4¸ö×Ö½ÚµÄÊýÒª±ÈÈ¡Ò»¸ö×Ö½ÚÒª¸ßЧ£¬Ò²¸ü·½±ã¡£ËùÒÔÔڽṹÌåÖÐÿ¸ö³ÉÔ±µÄÊ×µØÖ·¶¼ÊÇ4µÄÕûÊý±¶µÄ»°£¬È¡Êý¾ÝÔªËØʱ¾Í»áÏà¶Ô¸ü¸ßЧ£¬Õâ¾ÍÊÇÄÚ´æ¶ÔÆëµÄÓÉÀ´¡£Ã¿¸öÌض¨Æ½Ì¨ÉϵıàÒëÆ÷¶¼ÓÐ×Ô¼ºµÄĬÈÏ¡°¶ÔÆëϵÊý¡±(Ò²½Ð¶ÔÆëÄ£Êý)¡£³ÌÐòÔ±¿ÉÒÔͨ¹ýÔ¤±àÒëÃüÁî#pragma pack(n)£¬n=1,2,4,8,16À´¸Ä±äÕâһϵÊý£¬ÆäÖеÄn¾ÍÊÇÄãÒªÖ¸¶¨µÄ¡°¶ÔÆëϵÊý¡±¡£
¹æÔò£º
1¡¢Êý¾Ý³ÉÔ±¶ÔÆë¹æÔò£º½á¹¹(struct)(»òÁªºÏ(union))µÄÊý¾Ý³ÉÔ±£¬µÚÒ»¸öÊý¾Ý³ÉÔ±·ÅÔÚoffsetΪ0µÄµØ·½£¬ÒÔºóÿ¸öÊý¾Ý³ÉÔ±µÄ¶ÔÆë°´ÕÕ#pragma packÖ¸¶¨µÄÊýÖµºÍÕâ¸öÊý¾Ý³ÉÔ±×ÔÉí³¤¶ÈÖУ¬±È½ÏСµÄÄǸö½øÐС£
2¡¢½á¹¹(»òÁªºÏ)µÄÕûÌå¶ÔÆë¹æÔò£ºÔÚÊý¾Ý³ÉÔ±Íê³É¸÷×Ô¶ÔÆëÖ®ºó£¬½á¹¹(»òÁªºÏ)±¾ÉíÒ²Òª½øÐжÔÆ룬¶ÔÆ뽫°´ÕÕ#pragma packÖ¸¶¨µÄÊýÖµºÍ½á¹¹(»òÁªºÏ)×î´óÊý¾Ý³ÉÔ±³¤¶ÈÖУ¬±È½ÏСµÄÄǸö½øÐС£
3¡¢½áºÏ1¡¢2¿ÉÍƶϣºµ±#pragma packµÄnÖµµÈÓÚ»ò³¬¹ýËùÓÐÊý¾Ý³ÉÔ±³¤¶ÈµÄʱºò£¬Õâ¸önÖµµÄ´óС½«²»²úÉúÈκÎЧ¹û¡£
#include <stdio.h> #pragma pack(1)
struct BIR { int year; int month; }; struct STU { int num; //4 char name[15] ; //15 int score[2]; //8 struct BIR t; //8 }; int main() { printf("%d\n",sizeof(struct STU)); } |