[英]Why can't pointer to pointer, access struct members without a cast?
In C++, I was trying to access the struct members through double pointer headref
as shown below在 C++ 中,我试图通过双指针
headref
访问结构成员,如下所示
struct Node{
int data;
struct Node* next;
};
struct Node* head = new Node;
head->data = 10;
head->next = NULL;
struct Node** headref = &head;
However, accessing as *headref->data
produces errors while casting it ((Node*)*headref)->data
works.但是,作为
*headref->data
访问会在强制转换((Node*)*headref)->data
时产生错误。 Why?为什么?
This expression这个表达
*headref->data
is equivalent to相当于
*( headref->data )
It is not the same as the valid expression它与有效表达式不同
( *headref )->data
because the data member data
has no pointer type and you may not apply the unary operator * to it.因为数据成员
data
没有指针类型,您可能不会将一元运算符 * 应用于它。
This expression这个表达
((Node*)*headref)->data
is valid not due to the casting.有效不是由于铸造。 It is valid because if to remove the casting that is redundant you will get the valid edxpression
这是有效的,因为如果删除多余的强制转换,您将获得有效的 edxpression
( /*(Node*)*/ *headref)->data
shown above.如上所示。
If you chain operators together, it's always a good idea to make sure you remember their precedence correctly.如果将运算符链接在一起,确保正确记住它们的优先级总是一个好主意。 As listed here ,
operator->
has a higher precedence than the indirection *
.如此 处所列,
operator->
的优先级高于间接*
。 Hence因此
*headref->data
is interpreted as被解释为
*(headref->data)
which can't work.这是行不通的。 Instead, use
相反,使用
(*headref)->data
which is equivalent to ((Node*)headref)->data
.这相当于
((Node*)headref)->data
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.