简体   繁体   中英

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?

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?

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. Gcc says:

error: invalid conversion from 'int' to '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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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