afr0ck afr0ck - 2 months ago 10
C Question

How can i access an element from 2 structures pointers ?

I have a pointer & 2 different structures. The first structure has a member that is a void* pointer. Now i need to access a member of the second structure using the previous pointer to the first structure.

struct a {
void *ptrxx;
}

struct b {
int info;
}

struct a *ptr;


I need to do something like :

ptr->ptrxx->info;


But i have to do some kind of typecasting to let C know that
ptr->ptrxx
is a pointer to struct b. How can i do this in one expression (without the need of an extra pointer) ?

PS:I'm getting
error: request for member ***** in something not a structure or union.
(gcc).

Answer
((struct b *)(ptr->ptrxx))->info

Probably don't need all those parens, but it helps to show the order of what's happenning. Take the ptrxx member of struct a (which is a void *), cast it into a pointer to struct b, then take the info member of that.