简体   繁体   English

指向struct的指针是指向其第一个成员的指针吗?

[英]Is pointer to struct a pointer to its first member?

I'm learning how to work with struct s in C and wrote the following example: 我正在学习如何在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
}

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 : 我唯一能找到的关于结构类型布局的是Section 6.2.5 Types N1570的 Section 6.2.5 Types

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. 但这里没有任何关于填充的信息。

The padding at the start is covered by 6.7.2.1p15 (emphasis mine) 开始时的填充由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 . 结构对象中可能存在未命名的填充,但不是在其开头

So the address of a struct is the address of of its first member. 所以struct的地址是它的第一个成员的地址。 And following a pointer conversion, you are able to obtain one from the other. 在指针转换后,您可以从另一个获得一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM