我写了这段代码:
#include "stdio.h"
static int static_int;
static char static_char;
static float static_float;
static char *static_pointer;
static double static_double;
static int static_end;
int main()
{
printf("static int =%d\nstatic char = %c\nstatic float = %f\nstatic pointer =0x%x\nstatic doub le =%f\n",
static_int,static_char,static_float,static_pointer,static_double);
printf("\n\n");
printf("static int =0x%x\nstatic char =0x%x\nstatic float =0x%x\nstatic pointer =0x%x\nstatic_doub le =0x%x\nstatic end =0x%x\n",
&static_int,&static_char,&static_float,&static_pointer,&static_double,&static_end);
return 0;
}
我得到这个结果:
static int =0
static char =
static float = 0.000000
static pointer =0x0
static double =0.000000
static int =0x804a030
static char =0x804a034
static float =0x804a038
static pointer =0x804a03c
static_double =0x804a040
static end =0x804a048
我很困惑。
首先,为什么一个 char 占用 4 字节内存(应该只占用一个字节?)?
为什么 float 只占用 4 字节内存?我想它会自动变成双倍。 double 占用 8 个字节。
PS:我使用 SUSE 和 GCC。
最佳答案
- 字节而不是位。
- char 仅保存一个字节,下一个变量存储在 4 字节地址之外,因为 padding .
- float 在大多数现代系统上占用 4 个字节。它与转换为 double 无关。
关于c - 值如何存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18033360/