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

标签 c pointers struct alignment

我正在学习如何在 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/

相关文章:

c - 释放已分配的内存,消除错误

人物比较

c - Linux/C : Writing command-line arguments to a text file as separate lines?

c - malloc时指针之间的区别

将 void 指针转换为结构指针不会在结构内返回正确的指针

.net - 如何识别类型是否是自定义结构?

c - 在c中制作一长串加密子字符串

c# - 将指向结构的指针的 FieldOffset 设置为与固定字节数组相同的值

c - C中的堆栈代码一运行就崩溃并停止工作

c# - "Can' t 从类型 "Blah"隐式转换为类型 'string'