指向结构的指针是指向其第一个成员的指针吗? [英] Is pointer to struct a pointer to its first member?

查看:151
本文介绍了指向结构的指针是指向其第一个成员的指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning how to work with structs 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?

我唯一能找到的关于结构类型布局的是Section 6.2.5 Types. rel ="nofollow noreferrer"> N1570 :

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.

推荐答案

在结构对象中,非位字段成员和 驻留在哪个位域中的地址按以下顺序递增 他们被宣布.适当地指向结构对象的指针 转换后,指向其初始成员(或者该成员是 位域,然后到它所在的单元),反之亦然. 结构对象中可能存在未命名的填充,但结构对象中没有 开始.

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. And following a pointer conversion, you are able to obtain one from the other.

这篇关于指向结构的指针是指向其第一个成员的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆