Zack
Zack

Reputation: 1235

Store address information

I have a question about the following code:

//Definition of base used in ptr
void *base; 

int query(Win *ptr, void *baseptr)
{
    *(void**) baseptr = ptr->base;
    ...
}

Can I simply change the statement to the following?

baseptr = ptr->base;

Why does it cast baseptr to void **?

Upvotes: 0

Views: 63

Answers (2)

Philipp Murry
Philipp Murry

Reputation: 1682

You seemed to have overlooked the first * before the cast. It dereferences the pointer baseptr. This means, that the value of ptr->base is stored at the address where baseptr POINTS TO, and NOT in baseptr ITSELF. The cast happens because it tells the compiler that baseptr is now a pointer to another void pointer (i.e. the void pointer ptr->base).

Upvotes: 0

timrau
timrau

Reputation: 23058

Looks like baseptr is used as output parameter. The caller of query() should looks like:

void *base = NULL;
Win *win = something;
int result = query(win, &base);

Then, base in the caller function may be assigned the received value.

If you just write baseptr = ptr->base;, then it is the copy of base inside query() being updated. After query() returns, the pointer in caller is not updated at all.

Upvotes: 3

Related Questions