关于结构体所占用的长度,有两个原则:
1、各成员变量存放的起始地址相对于结构体的起始地址的偏移量必须为该变量的类型所占 用字节的倍数。
2、结构体的大小必须为成员中最大字节的整数倍
-
#include <stdio.h>
-
#include <stdlib.h>
-
-
struct a{
-
int a;
-
char b;
-
int c;
-
};
-
-
struct b{
-
char *a;
-
short b;
-
char c;
-
int d;
-
char e;
-
};
-
-
int main(void)
-
{
-
struct a a;
-
struct b b;
-
printf("a:%p b:%p c:%p sizeof(struct a):%d\n", &a.a, &a.b, &a.c, sizeof(struct a));
-
printf("a:%p b:%p c:%p d:%p e:%p sizeof(struct b):%d\n", &b.a, &b.b, &b.c, &b.d, &b.e, sizeof(struct b));
-
return 0;
-
}
执行结果
a:0xbfe5f6b0 b:0xbfe5f6b4 c:0xbfe5f6b8 sizeof(struct a):12
a:0xbfe5f6bc b:0xbfe5f6c0 c:0xbfe5f6c2 d:0xbfe5f6c4 e:0xbfe5f6c8 sizeof(struct b):16
阅读(4476) | 评论(0) | 转发(0) |