c - `char` 总是总是有 8 位吗?

标签 c memory

我一直认为:

  1. char 用字节表示,
  2. 一个字节总是可以被认为有 8 位,
  3. 那个 sizeof (char) 总是 1,
  4. 我可以分配的最大理论内存量(以 chars 计)是 RAM 的字节数(+交换空间)。

但是现在我已经阅读了 Wikipedia entry on the byte我不再那么确定了。

我的哪些假设是错误的?哪一个是危险的?

最佳答案

  1. 是的,charbyte几乎一样。一个字节是最小的可寻址内存量,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 byte

  2. A charCHAR_BIT位。它可以是任何数字(嗯,根据规范,8 或更大),但大多数情况下肯定是 8。有 16 位和 32 位的真实机器 char类型,虽然。 CHAR_BITlimits.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 for CHAR_BIT and MB_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

  3. sizeof(char) == 1 .总是。

    根据规范,6.5.3.4 部分 sizeof运算符,第 3 段:

    When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

  4. 您可以分配尽可能多的内存,只要您的系统允许您分配 - 标准中没有任何内容定义可能是多少。例如,您可以想象一台具有云存储支持的内存分配系统的计算机 - 您的可分配内存实际上可能是无限的。

    这是完整的规范部分 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 by size 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/

相关文章:

java - 惯用 scala 中 jvm 选项的指南

c - 将 float 拆分为两个简单整数?

c - 当某些非整数的无效输入时,打印语句开头的额外零

c - "signed or unsigned type"在此 C90 未定义行为定义中的含义是什么?

c++ - Qsort 基于 c 字符串中的列?

c# - 我怎样才能确定一个巨大的 C# 数据集的内存使用情况

c++ - 使用 DELETE 来节省内存,有人可以证明

c# - 通过 COM 互操作访问 C# 中的 protected 内存

memory - Stm32f4内存跳转

c - 为什么 getpagesize() 返回一个 int?