alignof(char)
可以不是 1 吗?
来自 unofficial cppreference.com wiki :
The weakest (smallest) alignment is the alignment of the types
char
,signed char
, andunsigned 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 typeschar
,signed char
, andunsigned char
shall 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 hastype char
,unsigned char
, orsigned char
, (or a qualified version thereof) the result is1
. 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
保证为2
,sizeof charArr[0]
= sizeof charArr[1]
= 1
。这意味着两个相邻的 char
对象代替了 2 个字节。
因此,可以推断“连续地址之间可以分配一个char的字节数”至少为1
。另外,char
的对齐方式必须是正整数,所以不能是1
以外的任何数字。
关于c++ - C(和 C++)中 char 的对齐是否保证为 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805521/