Reputation: 31
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?
Upvotes: 1
Views: 109
Reputation: 206737
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;
Upvotes: 1
Reputation: 15524
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.
Upvotes: 1
Reputation: 311054
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;
Upvotes: 4