Ç问:为什么CHAR实际上是在内存占用4字节? [英] C Question: why char actually occupies 4 bytes in memory?

查看:178
本文介绍了Ç问:为什么CHAR实际上是在内存占用4字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小程序来检查字符在我的记忆多少字节占据,它显示字符实际上是在内存占用4个字节。我知道这是主要是因为字对齐,并没有看到优势的焦炭仅为1个字节。为什么不使用4个字节对于char?

I wrote a small program to check how many bytes char occupies in my memory and it shows char actually occupies 4 bytes in memory. I understand it's mostly because of word alignment and don't see advantage of a char being only 1 byte. Why not use 4 bytes for char?

int main(void)
{
  int a;
  char b;
  int c;
  a = 0;
  b = 'b';
  c = 1;
  printf("%p\n",&a);
  printf("%p\n",&b);
  printf("%p\n",&c);
  return 0;
}

输出:
    0x7fff91a15c58
    0x7fff91a15c5f
    0x7fff91a15c54

Output: 0x7fff91a15c58 0x7fff91a15c5f 0x7fff91a15c54

更新:
我不相信的malloc将为焦炭仅分配1个字节,即使的sizeof(char)的作为参数,因为的malloc包含一个标头将可以确保头是字对齐通过。任何意见?

Update: I don't believe that malloc will allocate only 1 byte for char, even though sizeof(char) is passed as argument because, malloc contains a header will makes sure that header is word aligned. Any comments?

UPDATE2:
如果你被要求有效地使用内存没有填充,是唯一的方法是创建一个特殊的内存分配?或者是有可能禁用填充?

Update2: If you are asked to effectively use memory without padding, is the only way is to create a special memory allocator? or is it possible to disable padding?

推荐答案

您是int,焦炭,诠释

You have int, char, int

在这里看到的图像在为什么要限制字节对齐?
<一href=\"http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm\">http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm

See the image here under "Why Restrict Byte Alignment?" http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm

          Byte 0 Byte 1 Byte 2  Byte 3
0x1000               
0x1004  X0     X1     X2      X3
0x1008               
0x100C         Y0     Y1      Y2

如果它保存在他们的4个字节,1个字节和4个字节的形式,它会采取2个CPU周期来检索诠释三和一些比特转移获得的C用作一个int正确对齐的实际值。

If it had stored them in 4-byte, 1-byte and 4-byte form, it would have taken 2 cpu cycles to retrieve int c and some bit-shifting to get the actual value of c aligned properly for use as an int.

这篇关于Ç问:为什么CHAR实际上是在内存占用4字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆