C编译器可以在一个结构中的第一个元素之前增加填充? [英] Can a C compiler add padding before the first element in a structure?
问题描述
具体来说,我在想,如果我能做出这样的事情:
Specifically, I was wondering if I could make something like this:
typedef struct {
char *s; /* still a cstr, with '0' bit at end */
size_t len;
} str;
str *newstr(char *s) {/*...*/};
void freestr(str *s) {/*...*/};
和做这样的事情(把它与 STDLIB /串
功能CSTR):
and do things like this (treat it as a cstr with stdlib/string
functions):
int main() {
str *s = newstr("hello");
printf("The first character of '%s' is '%c'", *s, (*s)[0]);
freestr(s);
}
如果不是,它是不是一个大问题 - 当然,我真的不关心浪费一个字节。
If not, it's not a big deal—and, of course, I'm not really concerned about wasting a byte.
推荐答案
没有,这就是标准明确禁止将任何填充的地方。一个结构的第一构件和结构的地址的地址必须是相同的。
No, that's a place where the standard explicitly forbids placing any padding. The address of the first member of a struct and the address of the struct must be the same.
在C2011标准规定的n1570草案第6.7.2.1(15):
Section 6.7.2.1 (15) in the n1570 draft of the C2011 standard states:
在一个结构物中,非位字段部件和单元,其中位字段驻留有在其声明的顺序增加的地址。 一个指向结构对象,合适的转换,指向其初始成员(如该成员是一个位域,然后在它所在的单元),反之亦然。有可能是结构对象内无名填充,但不是在其开头。
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
(重点煤矿)
这篇关于C编译器可以在一个结构中的第一个元素之前增加填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!