我如何...理解这一点(padding invlolved)? [英] How do i...understand this(padding invlolved)?

查看:166
本文介绍了我如何...理解这一点(padding invlolved)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <string.h>

/*  Below structure1 and structure2 are same.
    They differ only in member's allignment */
//#pragma pack ( 1 )
struct structure1
{
        char  _1;
        short int _2;
        char _3;
};


int main()
{
    struct structure1 a;

    printf("size of structure1 in bytes : %d\n",sizeof(a));
    printf ( "\n   Address of id1        = %u", &a._1 );
    printf ( "\n   Address of id2        = %u", &a._2 );
    printf ( "\n   Address of name       = %u", &a._3 );


    getchar();
    return 0;
}





我的尝试:





What I have tried:

tried on 32 bit compiler!
why am i getting 6 bytes??shoulnt i get 8 bytes...as there i padding involved here!!
as it always reads 4 bytes at a time!!

推荐答案

简单:一个短的int是两个字节 - 那个意味着它的地址必须以两字节边界开始。因此,当您在它之前有一个char时,会添加一个额外的字节作为填充,以使整数达到适当的地址。类似地,填充应用于将整个结构向上舍入到适当的边界(或者它们的数组在每个第二个实例上都会未对齐)。

将其更改为:

Simple: a short int is two bytes - and that means it's address must start on a two byte boundary. So when you have a single char before it, an additional byte is added as padding to bring the integer up to the appropriate address. Similarly, padding is applied to "round up" the whole struct to an appropriate boundary (or an array of them would be misaligned on every second instance).
Change it to this:
struct structure1
{
        char  _1;
        char _3;
        short int _2;
};

并且它将是4个字节。


看看: C结构包装的失落艺术 [ ^ ]。


这篇关于我如何...理解这一点(padding invlolved)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆