在C中访问指针地址的结构成员 [英] Accessing struct member of pointer's address in C

查看:114
本文介绍了在C中访问指针地址的结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这本书,我找到了这段代码第14章中的代码段.

I'm reading this book, and I found this code snippet in Chapter 14.

struct kobject *cdev_get(struct cdev *p)
{
    struct module *owner = p->owner;
    struct kobject *kobj;
    if (owner && !try_module_get(owner))
        return NULL;
    kobj = kobject_get(&p->kobj);
    if (!kobj)
        module_put(owner);
    return kobj;
}

我知道这会取消引用p,然后cdev指针会访问其所有者成员

I understand that this dereferences p, a cdev pointer then accesses its owner member

p->owner // (*p).owner

但是,这是如何工作的?似乎它取消引用了cdev指针的内存地址,然后访问了指针本身的kobj成员?

However, how does this work? It seems like it dereferences the memory address of a cdev pointer then access the kobj member of the pointer itself?

&p->kobj // (*(&p)).kobj

我认为指针只不过是内存地址而已,所以我不了解它们如何拥有成员.如果它试图访问指针本身的成员,为什么不只是p.kobj?

I thought pointers weren't much more than memory addresses so I don't understand how they can have members. And if it was trying to access a member of the pointer itself, why not just do p.kobj?

推荐答案

根据p定义为struct cdev *pp很大程度上是一个内存地址",但这并不是全部是-它还附加了 type .

As per p being defined as struct cdev *p, p is very much a "memory address" but that's not all it is - it also has a type attached to it.

由于表达式*ptr是"ptr指向的对象",所以具有附加的类型,因此您可以从逻辑上进行(*ptr).member.

Since the expression *ptr is "the object pointed to by ptr", that also has the type attached, so you can logically do (*ptr).member.

而且,由于ptr->member(*ptr).member相同,因此也是有效的.

And, since ptr->member is identical to (*ptr).member, it too is valid.

最重要的是,您的论点是指针[不] 很多比内存地址更多"是正确的.但是它们稍微有点 :-)

Bottom line is, your contention that "pointers [aren't] much more than memory addresses" is correct. But they are a little bit more :-)

&ptr->member而言,您似乎将其读为(&ptr)->member,这是不正确的.

In terms of &ptr->member, you seem to be reading that as (&ptr)->member, which is not correct.

相反,根据C优先级规则,它实际上是&(ptr->member),表示该结构的成员的地址.

Instead, as per C precedence rules, it is actually &(ptr->member), which means the address of the member of that structure.

这些优先级规则实际上是由ISO C标准(在这种情况下为C11)指定的.在6.5 Expressions中,脚注85:

These precedence rules are actually specified by the ISO C standard (C11 in this case). From 6.5 Expressions, footnote 85:

该语法指定了运算符在表达式求值中的优先级,该优先级与此子节的主要子节的顺序相同,从最高优先级开始.

The syntax specifies the precedence of operators in the evaluation of an expression, which is the same as the order of the major subclauses of this subclause, highest precedence first.

而且,由于6.5.2 Postfix operators(覆盖->的位)早于6.5.3 Unary operators(覆盖&的位),这意味着->首先求值.

And, since 6.5.2 Postfix operators (the bit covering ->) comes before 6.5.3 Unary operators (the bit covering &), that means -> evaluates first.

这篇关于在C中访问指针地址的结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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