简体   繁体   English

运算符优先级和类型转换在这里如何工作

[英]How does operator precedence and typecasting work here

Okay, so I'm writing working on pointers here and I'm not sure how this piece of code works. 好的,所以我在这里编写指针的工作,并且不确定这段代码如何工作。

typedef struct linkedlist {
    void *obj;
    struct linkedlist *next;
} linkedlist;
linkedlist *p;

//some code here

int *newpointer = (*(int *)(p->next)->obj); //code chunk in question

If I need to typecast the void pointer 'obj' in the struct pointed to by p->next (assume it already exists) and copy it to 'newpointer' int pointer, am I doing it right? 如果我需要在p-> next所指向的结构中类型转换void指针'obj'(假设它已经存在)并将其复制到'newpointer'int指针,我是否正确?

int *newpointer = (*(int *)(p->next)->obj); //code chunk in question

If I need to typecast the void pointer 'obj' in the struct pointed to by p->next (assume it already exists) and copy it to 'newpointer' int pointer, am I doing it right? 如果我需要在p-> next所指向的结构中类型转换void指针'obj'(假设它已经存在)并将其复制到'newpointer'int指针,我是否正确?

No. The compiler would have told you that. 不。编译器会告诉您的。 You don't need all those parentheses either: 您也不需要所有这些括号:

int *newpointer = (int *)p->next->obj;

You are trying to initialize the pointer newpointer with the dereferenced value of the casted pointer which is an error. 您正在尝试使用转换指针的取消引用值初始化指针newpointer ,这是一个错误。 Gcc says: 海湾合作委员会说:

error: invalid conversion from 'int' to 'int*' 错误:从“ int”到“ int *”的无效转换

Remove the call to the dereference operator: 删除对取消引用运算符的调用:

int *newpointer = (int*) p->next->obj; // Also stripped unnecessary parentheses.

In C, the typecast operator has lower precedence than the member access operators. 在C语言中,类型转换运算符的优先级低于成员访问运算符的优先级。 Hence, 因此,

(int*)p->next->obj = (int*)(p->next->obj) = (int*)((p->next)->obj)

If the member access operators were of higher precedence, you would use: 如果成员访问运算符的优先级更高,则可以使用:

int *newpointer = (int*)(p->next->obj);

Since they are not, you can omit all the paratheses and use: 由于它们不是,因此您可以省略所有的参数并使用:

int *newpointer = (int*)p->next->obj;

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

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