C 编译器可以在结构中的第一个元素之前添加填充吗?

标签 c

具体来说,我想知道我是否可以做这样的事情:

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/

相关文章:

创建一个生成文件

c - 使用完整缓冲区的生产者-消费者算法

c - 为 ARM 交叉编译时 header 子目录错误

c++ - 有没有感觉 c++ 有时会减少解决问题的时间并增加句法、语义的严谨性?

GTK+ 中的 CSS 不起作用

c - 将.csv文件解析为C中的二维数组

c - 该程序的输出是什么以及如何输出?

将整数值转换为十六进制字符串

c - 2 个简单循环不能一起工作,段错误

c - 请求终端大小 [C - Linux]