简体   繁体   English

通过指针访问结构中的指针

[英]Accessing a pointer in a struct through a pointer

So I've been looking over structs while reading abut linked lists and came across a thought. 因此,我一直在查阅结构,同时阅读链接列表,并发现了一个想法。

How do I properly access a pointer in a struct using a pointer to the struct? 如何使用指向结构的指针正确访问结构中的指针?

For example I have a declaration of a struct as such: 例如,我有一个结构的声明:

typedef struct Sample{
    int x;
    int *y;
} Sample;

Sample test, *pter;  // Declare the struct and a pointer to it.
pter = &test;

So now I have a pointer to the struct and I know I can access the data in int x like this: pter->x and that is the same as this. 所以现在我有一个指向结构的指针,我知道我可以像这样访问int x的数据: pter->x ,这与此相同。 However I'm having trouble choosing/figuring out how to access *y through the pointer. 但是我在选择/弄清楚如何通过指针访问*y遇到了麻烦。

One of my friends say I should do it like this: *pter->y , however I'm thinking that it would make more sense to do it as such: pter->*y . 我的一个朋友说我应该这样做: *pter->y ,但是我认为这样做会更有意义: pter->*y Which is the right/only/proper/correct way to do it? 这是正确/唯一/正确/正确的方法吗? Would both of them work perhaps? 他们俩都会工作吗?

For value of y use pter->y , and for value stored at y use *pter->y (that is equivalent to *(pter->y) ). 对于y值,使用pter->y ,对于存储在y值,使用*pter->y (相当于*(pter->y) )。

Note: precedence of -> operator is higher then * Dereference operator that is why *pter->y == *(pter->y) 注意: ->运算符的优先级高于* Dereference运算符,这就是为什么*pter->y == *(pter->y)

Edit: on the basis of comment. 编辑:在评论的基础上。

The expression pter-> *y should be a syntax error as it can't be a valid expression because of following reasons. 表达式pter-> *y应该是语法错误,因为它不能是有效的表达式,原因如下。

  1. If * is interpreated as unary dereference operator and applied on y , then y is unknown variable name(without pter ). 如果*被解释为一元解除引用运算符并应用于y ,那么y是未知的变量名(没有pter )。
  2. If * is treated as as multiplication operator then -> can't appear before * . 如果*被视为乘法运算符,那么->不能出现在*之前。

So in both way it is compilation produces error. 因此,两种方式都是编译产生错误。

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

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