C/C++½á¹¹Ìå×Ö½Ú¶ÔÆë
[×¢]£º×î½üÔÚ×öUVCÃèÊö·ûµÄ±à¼¹¤¾ß£¬Óõ½ºÜ¶àµÄ½á¹¹£¬ÎªÁË·½±ã°Ñ½á¹¹Ìåд³ÉbinÎļþ£¬ÐèÒª°Ñ½á¹¹ÌåÖÐÌî³äµÄ×Ö½ÚÈ¥µô£¬ÔÚÍøÉÏËÑË÷µÃµ½ÕâƪÎÄÕ£¬¸Ð¾õͦºÃµÄ£¬×ª¹ýÀ´×ö¸ö¼ÍÄî¡£
½á¹¹Ìå(struct)µÄsizeofÖµ£¬²¢²»ÊǼòµ¥µÄ½«ÆäÖи÷ÔªËØËùÕ¼×Ö½ÚÏà¼Ó£¬¶øÊÇÒª¿¼Âǵ½´æ´¢¿Õ¼äµÄ×Ö½Ú¶ÔÆëÎÊÌâ¡£ÏÈ¿´ÏÂÃ涨ÒåµÄÁ½¸ö½á¹¹Ìå.
struct
{
char a;
short b;
char c;
}S1;
struct
{
char a;
char b;
short c;
}S2;
·Ö±ðÓóÌÐò²âÊԵóösizeof(S1)=6 , sizeof(S2)=4
¿É¼û£¬ËäÈ»Á½¸ö½á¹¹ÌåËùº¬µÄÔªËØÏàͬ£¬µ«ÒòΪÆäÖдæ·ÅµÄÔªËØÀàÐÍ˳Ðò²»Ò»Ñù£¬ËùÕ¼×Ö½ÚÒ²³öÏÖ²îÒì¡£Õâ¾ÍÊÇ×Ö½Ú¶ÔÆëÔÒò¡£Í¨¹ý×Ö½Ú¶ÔÆ룬ÓÐÖúÓÚ¼Ó¿ì¼ÆËã»úµÄÈ¡ÊýËٶȣ¬·ñÔò¾ÍµÃ¶à»¨Ö¸ÁîÖÜÆÚ¡£
×Ö½Ú¶ÔÆëÔÔò
½á¹¹ÌåĬÈϵÄ×Ö½Ú¶ÔÆëÒ»°ãÂú×ãÈý¸ö×¼Ôò£º
1) ½á¹¹Ìå±äÁ¿µÄÊ×µØÖ·Äܹ»±»Æä×î¿í»ù±¾ÀàÐͳÉÔ±µÄ´óСËùÕû³ý£»
2) ½á¹¹Ìåÿ¸ö³ÉÔ±Ïà¶ÔÓڽṹÌåÊ×µØÖ·µÄÆ«ÒÆÁ¿£¨offset£©¶¼ÊdzÉÔ±×ÔÉí´óСµÄÕûÊý±¶£¬ÈçÓÐÐèÒª±àÒëÆ÷»áÔÚ³ÉÔ±Ö®¼ä¼ÓÉÏÌî³ä×Ö½Ú£¨internal adding£©£»
3) ½á¹¹ÌåµÄ×Ü´óСΪ½á¹¹Ìå×î¿í»ù±¾ÀàÐͳÉÔ±´óСµÄÕûÊý±¶£¬ÈçÓÐÐèÒª±àÒëÆ÷»áÔÚ×îÄ©Ò»¸ö³ÉÔ±Ö®ºó¼ÓÉÏÌî³ä×Ö½Ú£¨trailing padding£©¡£
ͨ¹ýÕâÈý¸öÔÔò£¬¾Í²»ÄÑÀí½âÉÏÃæÁ½¸östructµÄ²îÒìÁË.
¶ÔÓÚstruct S1, ΪÁËʹshort±äÁ¿Âú×ã×Ö½Ú¶ÔÆä×¼Ôò(2), ¼´Æä´æ´¢Î»ÖÃÏà¶ÔÓڽṹÌåÊ×µØÖ·µÄoffsetÊÇ×ÔÉí´óС(shortÕ¼2¸ö×Ö½Ú)µÄÕûÊý±¶£¬±ØÐëÔÚ×Ö½ÚaºóÃæÌî³äÒ»¸ö×Ö½ÚÒÔ¶ÔÆ룻ÔÙÓÉ×¼Ôò(3),ΪÁË Âú×ã½á¹¹Ìå×Ü´óСΪshort´óСµÄÕûÊý±¶£¬±ØÐëÔÙÔÚcºóÃæÌî³äÒ»¸ö×Ö½Ú¡£
¶ÔÓÚstruct S2, È´²»±ØÈçÉÏËùÊöµÄÌî³ä×Ö½Ú£¬ÒòΪÆäÖ±½Ó˳Ðò´æ´¢ÒѾÂú×ãÁ˶ÔÆë×¼Ôò¡£
Èç¹û½«ÉÏÃæÁ½¸ö½á¹¹ÌåÖеÄshort¶¼¸ÄΪint(Õ¼4¸ö×Ö½Ú), ÄÇô»áÔõôÑùÄØ£¿ ³ÌÐòµÃ³ösizeof(S1)=12, sizeof(S2)=8
ÀûÓÃÉÏÃæµÄ×¼Ôò£¬Ò²²»ÄѼÆËãµÃ³öÕâÑùµÄ½á¹û¡£S1ÖÐÔÚaºóÃæÌî³ä3¸ö×Ö½Ú¡¢ÔÚcºóÃæÌî³ä3¸ö×Ö½Ú£¬ÕâÑùÒ»¹²12¸ö×Ö½Ú£»S2ÖÐÔÚa¡¢b˳Ðò´æ´¢Ö®ºóÌî³äÁ½¸ö×Ö½ÚÓÃÒÔ¶ÔÆ䣬ÕâÑùÒ»¹²¾Í8¸ö×Ö½Ú¡£
µ±È»£¬ÔÚijЩʱºòÒ²¿ÉÒÔÉèÖÃ×Ö½Ú¶ÔÆ뷽ʽ¡£Õâ¾ÍÐèҪʹÓà #pragma pack ¡£
#pragma pack(push) //ѹջ±£´æ
#pragma pack(1)// ÉèÖÃ1×Ö½Ú¶ÔÆë
struct
{
char a;
short b;
char c;
}S1;
#pragma pack(pop) // »Ö¸´ÏÈÇ°ÉèÖÃ
ÈçÉÏËùʾ£¬½«¶ÔÆ䷽ʽÉèΪ1×Ö½Ú¶ÔÆë£
Ïà¹ØÎĵµ£º
ÒÔǰѧÉúʱ´úµÄʱºò¾ÍÓÐÓöµ½¹ýÕâ¸öÎÊÌ⣬²»¹ýûȥÉ£»
ÏÖÔÚÒ²ÊÇÀÏÎÊÌ⣬ÆäʵºÜ¼òµ¥£¬¾ÍÊÇΪÁË·ÀÖ¹#includeÁ½¸öÍ·ÎļþµÄʱºò£¬°ÑµÚÒ»¸öÍ·ÎļþµÄ×îºóÒ»ÐÐºÍ µÚ¶þ¸öÍ·ÎļþµÄµÚÒ»ÐÐÆ´½Ó³ÉÒ»ÐУ»ºÇºÇ£¬ÆäʵºÜ¶àÎÊÌⶼºÜ¼òµ¥£¬¶øÇÒºÜÒþ±Î£¬Ö»ÊÇÎÒÃǺܶàʱºòûȥעÒ⣡ ......
CºÍC++±à³ÌºÍѧϰÎĵµ
1 :Ö¸Õë±äÁ¿Ãû³ÆÒÔpΪÊ××Ö·û£¬ÕâÊdzÌÐòԱͨ³£ÔÚ¶¨ÒåÖ¸ÕëʱµÄÒ»¸öÏ°¹ß
2 :har * p; (int *)p °ÑpÇ¿ÖÆת»»ÎªintÐÍ   ......
ÔÚÌÖÂÛÈ«¾Ö±äÁ¿Ö®Ç°ÎÒÃÇÏÈÒªÃ÷°×¼¸¸ö»ù±¾µÄ¸ÅÄ
1. ±àÒëµ¥Ôª(Ä£¿é)£º
ÔÚIDE¿ª·¢¹¤¾ß´óÐÐÆäµÀµÄ½ñÌ죬¶ÔÓÚ±àÒëµÄһЩ¸ÅÄîºÜ¶àÈËÒѾ²»ÔÙÇå³þÁË£¬ºÜ¶à³ÌÐòÔ±×îŵľÍÊÇ´¦ÀíÁ¬½Ó´íÎó(LINK ERROR), ÒòΪËü²»Ïñ±àÒë´íÎóÄÇÑù¿ÉÒÔ¸ø³öÄã³ÌÐò´íÎóµÄ¾ßÌåλÖã¬Äã³£³£¶ÔÕâÖÖ´íÎó¸Ðµ½°ÃÄÕ£¬µ«ÊÇÈç¹ûÄã¾ ......
ÐÂÈ˸տªÊ¼Íæ×îºÃ½¨¸öÃâ·ÑºÅÏÈÊìϤÏÂÓÎÏ·£¬ÏÈ°ÑÐÂÊֽ̳Ì×öÍ棬½Ì³ÌÒªÂýÂý×ö£¬°Ñÿһ²½½ÌµÄ¶¼Ñ§µ½¡£ÎÒÇ¿ÁÒBS×öÍê½Ì³Ì»¹²»»áÍê˵½Ì³Ì²»ºÃµÄÈË£¬ÒÔÇ°ÎÒÍêÅ··þ¶¼ÊÇ×öÍê½Ì³Ì¾ÍÄÜ¿ªÊ¼ÍêÁË£¬ÎÒ»¹ÊÇÓõĽðɽ¿ìÒë2002µÄ£¬¸Â¸Â¡£
ÑÔ¹éÕý´«£¬ÐÂÈË×öÍê½Ì³Ì×îºóµÄ2¸öÈÎÎñÊÖÉϸÃÓÐ10W¶àÁË£¨×îºóµÄÄǸö´úÀíÈËÈÎÎñ²»×ö½Ì³ÌÒ²¿ÉÒÔÖ±½Ó×ö£©£¬ ......