平台:RHEL 6 64bit
例子:
[clef@rhel6164 struct]$ cat ./book.c
#include <stdio.h>
#define MAXTITL 41
struct book{
//char title[MAXTITL];
float *p;
};
int main(void)
{
struct book library;
char *ptr;
//printf("%d\n",sizeof(book)); 如果直接去统计book结构所所占用的空间,就会报(‘book’ undeclared)
printf("strut book library: %d\n",sizeof(library));
printf("char *ptr: %d\n",sizeof(ptr));
return 0;
}
编译&运行:
[clef@rhel6164 struct]$ gcc ./book.c
[clef@rhel6164 struct]$ ./a.out
strut book library: 8
char *ptr: 8
上面的book结构里面仅包含了一个指向float的指针(
表示一个地址),因为这里的平台是用的64bit,并且sizeof是以字节(8bit)来显示,所以这里book结构的大小显示为8字节,同样这里定义了一个指向char类型的指针,同样是因为上面的原因,结果一样是8字节.
如果把上面book结构里面的数组title定义解注释,结果将会是56字节,而不是49(41+8)字节。因为64bit平台是以8的倍数来分配内存空间的,虽然上面的title数组只有41字节,但是同样会分配48字节给数组title,这样一来一共就是56字节。
[clef@rhel6164 struct]$ cat book.c
#include <stdio.h>
#define MAXTITL 41
struct book{
char title[MAXTITL];
float *p;
};
int main(void)
{
struct book library;
char *ptr;
//printf("%d\n",sizeof(book));
printf("strut book library: %d\n",sizeof(library));
printf("char *ptr: %d\n",sizeof(ptr));
return 0;
}
[clef@rhel6164 struct]$ gcc ./book.c
[clef@rhel6164 struct]$ ./a.out
strut book library: 56
char *ptr: 8