gpt4 book ai didi

c - 指向结构的指针是指向其第一个成员的指针吗?

转载 作者:太空狗 更新时间:2023-10-29 15:17:23 27 4
gpt4 key购买 nike

我正在学习如何在 C 中使用 struct 并编写了以下示例:

#include <stdio.h>
#include <stdlib.h>

struct s1{
unsigned short member;
};

int main()
{
struct s1 *s1_ptr = malloc(sizeof(*s1_ptr));
s1_ptr -> member = 10;
printf("Member = %d\n", *s1_ptr); // Member = 10
}

问题:能否保证在所有情况下指向结构的指针与指向其第一个元素的指针完全相同?

在这种特殊情况下,它按我的预期工作,但我不确定它是否得到保证。编译器是否可以在一开始就随意插入一些填充?

关于结构类型布局,我唯一能找到的是 N1570第 6.2.5 节类型 :

A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

但是这里没有关于填充的内容。

最佳答案

开头的填充被 6.7.2.1p15 覆盖(强调我的)

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/53578631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com