当前位置: 技术问答>linux和unix
Solaris下 C 语言编译时结构体成员对齐问题,请教!急!先谢了!
来源: 互联网 发布时间:2015-02-23
本文导语: TestSize.c: #include struct cos_prodlist{ char mode; char submode; char sts; char substs; char *bufad; unsigned int bufsz; short menmode; char baitai[1]; char kmsbt; short year; char month; char day; char menname[20]; char ...
TestSize.c:
#include
struct cos_prodlist{
char mode;
char submode;
char sts;
char substs;
char *bufad;
unsigned int bufsz;
short menmode;
char baitai[1];
char kmsbt;
short year;
char month;
char day;
char menname[20];
char hanname[20];
char hzkname[24];
unsigned int menid;
short ysomode;
unsigned short sid;
unsigned short recsu;
char resend;
unsigned char spflag;
char sozaiid[20];
char uid[12];
};
struct cos_prod_param {
unsigned short recsu;
unsigned short rslt;
};
struct cos_prod {
struct cos_prod_param param;
struct cos_prodlist p[1];
};
void main()
{
struct cos_prod spara;
struct cos_prodlist *p;
p = (struct cos_prodlist *)((long)(&spara) + sizeof(struct cos_prod_param));
printf("-----&spara=%p-----n",&spara);
printf("-----&spara.param=%p-----n",&(spara.param));
printf("-----sizeof(struct cos_prod_param)=%d----n",sizeof(struct cos_prod_param));
printf("-----after calculate p=%p-----n",p);
printf("-----in fact p=%p-----n",(spara.p));
}
如上一段代码用下列命令编译:cc -xmemalign=2s -xarch=v9 -O -o TestSize TestSize.c
运行 TestSize
结果:
-----&spara=ffffffff7ffff2a0-----
-----&spara.param=ffffffff7ffff2a0-----
-----sizeof(struct cos_prod_param)=4----
-----after calculate p=ffffffff7ffff2a4-----
-----in fact p=ffffffff7ffff2a8-----
为什么自己计算的结构体地址和实际所指向的地址不同?
#include
struct cos_prodlist{
char mode;
char submode;
char sts;
char substs;
char *bufad;
unsigned int bufsz;
short menmode;
char baitai[1];
char kmsbt;
short year;
char month;
char day;
char menname[20];
char hanname[20];
char hzkname[24];
unsigned int menid;
short ysomode;
unsigned short sid;
unsigned short recsu;
char resend;
unsigned char spflag;
char sozaiid[20];
char uid[12];
};
struct cos_prod_param {
unsigned short recsu;
unsigned short rslt;
};
struct cos_prod {
struct cos_prod_param param;
struct cos_prodlist p[1];
};
void main()
{
struct cos_prod spara;
struct cos_prodlist *p;
p = (struct cos_prodlist *)((long)(&spara) + sizeof(struct cos_prod_param));
printf("-----&spara=%p-----n",&spara);
printf("-----&spara.param=%p-----n",&(spara.param));
printf("-----sizeof(struct cos_prod_param)=%d----n",sizeof(struct cos_prod_param));
printf("-----after calculate p=%p-----n",p);
printf("-----in fact p=%p-----n",(spara.p));
}
如上一段代码用下列命令编译:cc -xmemalign=2s -xarch=v9 -O -o TestSize TestSize.c
运行 TestSize
结果:
-----&spara=ffffffff7ffff2a0-----
-----&spara.param=ffffffff7ffff2a0-----
-----sizeof(struct cos_prod_param)=4----
-----after calculate p=ffffffff7ffff2a4-----
-----in fact p=ffffffff7ffff2a8-----
为什么自己计算的结构体地址和实际所指向的地址不同?
|
你用了-xarch=v9参数,编译器使用64位对齐,
所以cos_prod.param占了4个bytes,然后在补
4 bytes对齐。
所以cos_prod.param占了4个bytes,然后在补
4 bytes对齐。
|
对齐的问题我从来都是让编译器自己去做:)
|
真是挺奇怪的……
可惜我啥都不会
顶!
可惜我啥都不会
顶!