c++ - C(和 C++)中 char 的对齐是否保证为 1?

标签 c++ c language-lawyer

alignof(char) 可以不是 1 吗?

来自 unofficial cppreference.com wiki :

The weakest (smallest) alignment is the alignment of the types char, signed char, and unsigned char, and it is usually 1.

“通常”似乎暗示它可能是别的东西。

C 标准中关于 char 对齐的唯一规定是(C11 N1570 6.2.8 第 1 段):

The alignment requirement of a complete type can be queried using an _Alignof expression. The types char, signed char, and unsigned charshall have the weakest alignment requirement.

但是,请考虑对齐的定义(C11 N1570 6.2.8 第 1 段,并且对于 C++11 的定义类似):

An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.

据此,由于 sizeof(char) ≡ 1,表示相邻char元素之间的距离只能是1字节。

这有意义吗?

最佳答案

是的。尽管标准中没有明确规定此声明,但我想可以从中推断出:

N1570 6.5.3.4 The sizeof and _Alignof operators

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array.

char为例。假设我们有一个 char charArr[2];sizeof charArr保证为2sizeof charArr[0] = sizeof charArr[1] = 1。这意味着两个相邻的 char 对象代替了 2 个字节。

因此,可以推断“连续地址之间可以分配一个char的字节数”至少为1。另外,char的对齐方式必须是正整数,所以不能是1以外的任何数字。

关于c++ - C(和 C++)中 char 的对齐是否保证为 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805521/

相关文章:

c++ - GLEW 库和代码:: block

具有静态类成员的 C++ 模板类

c - 为什么返回带有字符串文字的 const char * 的函数有效?

c++ - 是否可以在调用后自动推断指向三元中成员重载函数的指针的类型?

c - 重新解释适当对齐的指向具有声明类型的对象的指针

c++ - 在 C++ 中,为什么我不能使用两个默认的随机引擎生成独立的随机整数样本

c++ - 使用 C++ 模板切换策略/算法

c - 使用动态内存分配在函数返回时中止陷阱 6

c - 如何在 C 中使用 strcmp 将用户输入与文本文件进行比较?

C 预处理器 : what is the motivation behind treating undefined macro as 0?