公 告

欢迎各位网友添加友情链接,在您添加本博客:http://linux0818.blogspot.com/ 做为链接后, E-mail:linux0818@gmail.com给我,我将将您的网址添加到本博客。

2008年10月14日星期二

struct结构体中成员类型长度

下面两个实例,求出结构体变量的总长度和其中每个成员的长度,试试看:
1)
#include <stdio.h>
#pragma pack(1)     //按位对齐,默认按4位对齐,这里设置按1位对齐
int main(int argc,char **argv)
{
struct abc{
        int x;
        char y[4];
        char z[2];
        long m;
        char *p;
        int *q;
        float n;
        int j;
        short k;
        double i;
}value;
printf("struct abc length= %d\n",sizeof(struct abc));
//printf("value length= %d\n",sizeof(value));//等同上面
printf("int x length= %d\n",sizeof(value.x));
printf("char y[3] length= %d\n",sizeof(value.y));
printf("char z[2] length= %d\n",sizeof(value.z));
printf("long m length= %d\n",sizeof(value.m));
printf("char *p length= %d\n",sizeof(value.p));
printf("int *q length= %d\n",sizeof(value.q));
printf("float n length= %d\n",sizeof(value.n));
printf("int j length= %d\n",sizeof(value.j));
printf("short k length= %d\n",sizeof(value.k));
printf("double i length= %d\n",sizeof(value.i));
return 0;
}
2)
#include <stdio.h>
int main(int argc,char **argv)
{
struct abc{
        int x;
        char y[4];
        char z[2];//结构体没满4个字节以4个字节对齐
        long m;
        char *p;
        int *q;
        float n;
        int j;
        short k;
        double i;
}value;
printf("struct abc length= %d\n",sizeof(struct abc));
printf("value length= %d\n",sizeof(value));//等同上面
printf("int x length= %d\n",sizeof(value.x));
printf("char y[3] length= %d\n",sizeof(value.y));
printf("char z[2] length= %d\n",sizeof(value.z));
printf("long m length= %d\n",sizeof(value.m));
printf("char *p length= %d\n",sizeof(value.p));
printf("int *q length= %d\n",sizeof(value.q));
printf("float n length= %d\n",sizeof(value.n));
printf("int j length= %d\n",sizeof(value.j));
printf("short k length= %d\n",sizeof(value.k));
printf("double i length= %d\n",sizeof(value.i));
return 0;
}
运行后其结果如下:
1)
struct abc length= 40
value length= 40
int x length= 4
char y[3] length= 4
char z[2] length= 2
long m length= 4
char *p length= 4
int *q length= 4
float n length= 4
int j length= 4
short k length= 2
double i length= 8
2)
struct abc length= 44
value length= 44
int x length= 4
char y[3] length= 4
char z[2] length= 2
long m length= 4
char *p length= 4
int *q length= 4
float n length= 4
int j length= 4
short k length= 2
double i length= 8
仔细看看,不同吧。


--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/

没有评论:

发表评论