我一直认为:
char
用字节表示,- 一个字节总是可以被认为有 8 位,
- 那个
sizeof (char)
总是1
, - 我可以分配的最大理论内存量(以
char
s 计)是 RAM 的字节数(+交换空间)。
但是现在我已经阅读了 Wikipedia entry on the byte我不再那么确定了。
我的哪些假设是错误的?哪一个是危险的?
最佳答案
是的,
char
和byte
几乎一样。一个字节是最小的可寻址内存量,char
也是如此。在 C.char
总是大小为 1。根据规范,3.6 字节部分:
byte
addressable unit of data storage large enough to hold any member of the basic character set of the execution environment
以及3.7.1 部分字符:
character
single-byte character
<C> bit representation that fits in a byteA
char
有CHAR_BIT
位。它可以是任何数字(嗯,根据规范,8 或更大),但大多数情况下肯定是 8。有 16 位和 32 位的真实机器char
类型,虽然。CHAR_BIT
在limits.h
中定义.根据规范,5.2.4.2.1 整数类型的大小
<limits.h>
部分:The values given below shall be replaced by constant expressions suitable for use in
#if
preprocessing directives. Moreover, except forCHAR_BIT
andMB_LEN_MAX
, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.— 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 段:When applied to an operand that has type
char
,unsigned char
, orsigned char
, (or a qualified version thereof) the result is 1.您可以分配尽可能多的内存,只要您的系统允许您分配 - 标准中没有任何内容定义可能是多少。例如,您可以想象一台具有云存储支持的内存分配系统的计算机 - 您的可分配内存实际上可能是无限的。
这是完整的规范部分 7.20.3.3
malloc
功能:Synopsis
1
#include <stdlib.h>
void *malloc(size_t size);
Description
2 The
malloc
function allocates space for an object whose size is specified bysize
and whose value is indeterminate.Returns
3 The
malloc
function returns either a null pointer or a pointer to the allocated space.这就是规范的全部内容,因此实际上没有任何可以依赖的限制。
关于c - `char` 总是总是有 8 位吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9727465/