具体来说,我想知道我是否可以做这样的事情:
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/string
函数的 cstr):
int main() {
str *s = newstr("hello");
printf("The first character of '%s' is '%c'", *s, (*s)[0]);
freestr(s);
}
如果不是,那也没什么大不了的——当然,我真的不担心浪费一个字节。
最佳答案
不,这是标准明确禁止放置任何填充的地方。结构体的第一个成员的地址和结构体的地址必须相同。
C2011 标准的 n1570 草案第 6.7.2.1 (15) 节指出:
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 编译器可以在结构中的第一个元素之前添加填充吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13210239/