如果 char 比 int 具有更严格的对齐要求,那么这个联合会起作用吗?
最近,我遇到了以下代码片段,它试图确保 i
的所有字节(仅此而已)都可以作为 c
的单个元素进行访问:
union {
int i;
char c[sizeof(int)];
};
现在这似乎是一个很好的选择想法,但我想知道标准是否允许 char 的对齐要求比 int 的对齐要求更严格的情况。
换句话说,是否有可能有一个四字节 int 需要在四字节边界上与一字节 char 对齐(根据定义,它是一个字节,请参见下文) )需要在十六字节边界上对齐吗?
这会影响上面联合的使用吗?
有两件事需要注意。
我在这里具体谈论标准允许的内容,而不是健全的实现者/架构将提供的内容。
我我在 ISO C 意义上使用术语“字节”,它是
char
的宽度,不一定是 8 位。
Recently I came across the following snippet, which is an attempt to ensure all bytes of i
(nad no more) are accessible as individual elements of c
:
union {
int i;
char c[sizeof(int)];
};
Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char
are more restrictive than that for int
.
In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char
(it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?
And would this stuff up the use of the union above?
Two things to note.
I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.
I'm using the term "byte" in the ISO C sense, where it's the width of a
char
, not necessarily 8 bits.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有任何类型比其大小有更严格的对齐要求(因为数组的工作方式),并且
sizeof(char)
为 1。如果不明显:
sizeof(T [N])
是sizeof(T)*N
。sizeof
以char
为单位;所有类型都表示为固定数量的字节 (char
),该数字就是它们的大小。详细信息请参见 6.2.6(类型的表示)。(char *)&A[1] - (char *)&A[0]
等于sizeof A [0]
。T
的对齐要求不大于sizeof(T)
(实际上它除以sizeof(T)
)No type can ever have stricter alignment requirements than its size (because of how arrays work), and
sizeof(char)
is 1.In case it's not obvious:
sizeof(T [N])
issizeof(T)*N
.sizeof
is in units ofchar
; all types are represented as a fixed number of bytes (char
), that number being their size. See 6.2.6 (Representation of Types) for details.T A[2];
,(char *)&A[1] - (char *)&A[0]
is equal tosizeof A[0]
.T
is no greater thansizeof(T)
(in fact it dividessizeof(T)
)看看此帖子。在那里,我对 C Unions 的实用性提出了质疑,并得到了一些有趣的见解。重要的是,该标准根本无法确保不同字段的一致性!
编辑:paxdiablo,刚刚注意到你是回答这个问题的人之一,所以你可能应该熟悉这个限制。
Have a look at this thread. There, I questioned the usefulness of C Unions and there are some interesting insights. The important thing is that the Standard does not ensure the alignment of the different fields at all!
EDIT: paxdiablo, just noticed you were one of the guys answering that question, so you should probably be familiar with this limitation.