指向结构的指针是指向其第一个成员的指针吗? [英] Is pointer to struct a pointer to its first member?
问题描述
我正在学习如何在C语言中使用struct
,并编写了以下示例:
I'm learning how to work with struct
s in C and wrote the following example:
#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
}
问题: 是否可以确保在所有情况下指向结构的指针与指向其第一个元素的指针完全相同?
QUESTION: Is it guaranteed that in all cases a pointer to a struct is a exactly the same pointer to its first element?
在这种特殊情况下,它可以按我的预期工作,但是我不确定是否可以保证.编译器是否可以在一开始就自由插入一些填充?
In this particular case it works as I expected, but I'm not sure if it is guaranteed. Is compiler free to insert some padding in the very beginning?
我唯一能找到的关于结构类型布局的是
The only I could find about the structure type layout is the Section 6.2.5 Types
of N1570:
结构类型描述了按顺序分配的非空集 成员对象(在某些情况下是不完整的数组), 每个名称都有一个可选的名称,并且可能不同 类型.
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.
但是这里没有关于填充的内容.
But there is nothing about padding here.