问题描述
我一直认为:
- 一个
char
用一个字节表示, - 一个字节总是可以被认为有 8 位,
- 那个
sizeof (char)
总是1
, - 并且我可以分配的最大理论内存量(以
char
s 计算)是 RAM 的字节数(+ 交换空间).
- that a
char
is represented by a byte, - that a byte can always be counted upon to have 8 bits,
- that
sizeof (char)
is always1
, - and that the maximum theoretical amount of memory I can allocate (counted in
char
s) is the number of bytes of RAM (+ swap space).
但现在我已经阅读了维基百科关于字节的条目我不是这样确定了.
But now that I've read the Wikipedia entry on the byte I'm not so sure anymore.
我的哪个(些)假设是错误的?哪些是危险的?
Which one(s) of my assumptions is wrong? Which one(s) is dangerous?
推荐答案
是的,
char
和byte
几乎相同.一个字节是最小的可寻址内存量,C 中的char
也是如此.char
的大小始终为 1.
Yes,
char
andbyte
are pretty much the same. A byte is the smallest addressable amount of memory, and so is achar
in C.char
always has size 1.
来自规范,3.6 字节:
字节
大到足以容纳执行环境基本字符集的任何成员的可寻址数据存储单元
addressable unit of data storage large enough to hold any member of the basic character set of the execution environment
和部分3.7.1字符:
字符
单字节字符
<C>适合一个字节的位表示
single-byte character
<C> bit representation that fits in a byte
char
有 CHAR_BIT
位.它可以是任何数字(好吧,根据规范是 8 或更大),但绝对是最常见的 8.不过,也有具有 16 位和 32 位 char
类型的真实机器.CHAR_BIT
在 limits.h
中定义.
A char
has CHAR_BIT
bits. It could be any number (well, 8 or greater according to the spec), but is definitely most often 8. There are real machines with 16- and 32-bit char
types, though. CHAR_BIT
is defined in limits.h
.
从规范中,5.2.4.2.1 整数类型的大小部分:
From the spec, section 5.2.4.2.1 Sizes of integer types <limits.h>
:
下面给出的值应替换为适用于 #if
预处理指令的常量表达式.此外,除了 CHAR_BIT
和 MB_LEN_MAX
之外,以下内容将替换为与以下内容具有相同类型的表达式一个表达式,它是根据整数提升转换的相应类型的对象.它们的实现定义的值在幅度(绝对值)上应等于或大于所示值,并具有相同的符号.
——不是位域的最小对象的位数(字节)
CHAR_BIT
; 8
— number of bits for smallest object that is not a bit-field (byte)
CHAR_BIT
8
sizeof(char) == 1
.总是.
来自规范,部分 6.5.3.4 sizeof
运算符,第 3 段:
From the spec, section 6.5.3.4 The sizeof
operator, paragraph 3:
当应用于具有 char
、unsigned char
或 signed char
,(或其限定版本)结果为 1.
您可以分配系统允许分配的尽可能多的内存 - 标准中没有定义可能有多少.例如,您可以想象一台具有云存储支持的内存分配系统的计算机 - 您的可分配内存实际上可能是无限的.
You can allocate as much memory as your system will let you allocate - there's nothing in the standard that defines how much that might be. You could imagine, for example, a computer with a cloud-storage backed memory allocation system - your allocatable memory might be practically infinite.
这里是完整的规范部分 7.20.3.3 malloc
函数:
Here's the complete spec section 7.20.3.3 The malloc
function:
概要
1 #include
void *malloc(size_t size);
1 #include <stdlib.h>
void *malloc(size_t size);
说明
2 malloc
函数为其大小由 size
指定且值为不确定.
2 The malloc
function allocates space for an object whose size is specified by size
and whose value is indeterminate.
退货
3 malloc
函数返回空指针或指向已分配空间的指针.
3 The malloc
function returns either a null pointer or a pointer to the allocated space.
这就是规范的全部内容,因此您实际上没有任何可以依赖的限制.
That's the entirety of the specification, so there's not really any limit you can rely on.
这篇关于`char` 总是-总是-总是有 8 位吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!