c - 值如何存储在内存中?

标签 c memory bit

我写了这段代码:

#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。

最佳答案

  1. 字节而不是位。
  2. char 仅保存一个字节,下一个变量存储在 4 字节地址之外,因为 padding .
  3. float 在大多数现代系统上占用 4 个字节。它与转换为 double 无关。

关于c - 值如何存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18033360/

相关文章:

windows - 当物理内存中的可用空间非常低时,Windows 是否仍能分配内存?

c - 如何在 Linux 上调试内存损坏

c++ - 在新建和删除操作中花费了意外的时间

位运算问题

c - 编写一个函数来返回节点的位置

c++ - C函数反转char数组字符串

c - 如何将字符串写入C中的文件?

PHP 位掩码在应该为假时说真

谁能解释一下这个简短的 C 操作的输出吗?

c - 大输入数频程序