昨天同事遇到的问题,以前没注意到。
如果定义以下结构体:
struct s1{
char i;
char j;
}s1_1;
那么sizeof(s1_1)等于2,但是若定义如下:
struct s2{
char i;
int j;
}s2_1;
那么sizeof(s2_1)等于4。看来结构体所占空间大小与单个元素应该占用的空间大小不是简单相加。不同的编译器其结果也不同。如下是测试程序:
#include
#define SET_STRUCT(p) { \
p->i = 1; \
p->j = 2; \
p->k = 3; \
pp = (char *)p; \
}
#define PRINT(str) { \
printf("%d\n",sizeof(str)); \
for(s = 0;s < sizeof(str);s++) \
printf(" 0x%X %d \n", pp+s, *(pp+s)); \
printf("\n"); \
}
int main()
{
struct sccc{
char i;
char j;
char k;
}ccc, *p1;
struct scci{
char i;
char j;
int k;
}cci, *p2;
struct sc2i{
char i;
int j;
int k;
}c2i, *p3;
struct scill{
char i;
int j;
long long k;
}cill, *p4;
char *pp;
int s;
p1 = &ccc;
SET_STRUCT(p1);
printf("c,c,c\n");
PRINT(ccc);
p2 = &cci;
SET_STRUCT(p2);
printf("c,c,i\n");
PRINT(cci);
p3 = &c2i;
SET_STRUCT(p3);
printf("c,i,i\n");
PRINT(c2i);
p4 = &cill;
SET_STRUCT(p4);
printf("c,i,ll\n");
PRINT(cill);
return 0;
}
用gcc在windows下编译,执行结果:
c,c,c
3
0x22EE90 1
0x22EE91 2
0x22EE92 3
c,c,i
8
0x22EE80 1
0x22EE81 2
0x22EE82 -128
0x22EE83 124
0x22EE84 3
0x22EE85 0
0x22EE86 0
0x22EE87 0
c,i,i
12
0x22EE60 1
0x22EE61 0
0x22EE62 0
0x22EE63 0
0x22EE64 2
0x22EE65 0
0x22EE66 0
0x22EE67 0
0x22EE68 3
0x22EE69 0
0x22EE6A 0
0x22EE6B 0
c,i,ll
16
0x22EE40 1
0x22EE41 0
0x22EE42 0
0x22EE43 0
0x22EE44 2
0x22EE45 0
0x22EE46 0
0x22EE47 0
0x22EE48 3
0x22EE49 0
0x22EE4A 0
0x22EE4B 0
0x22EE4C 0
0x22EE4D 0
0x22EE4E 0
0x22EE4F 0
阅读(1220) | 评论(0) | 转发(0) |