Reputation: 1204
We are returning a pointer to a struct in one of our functions. When we print out one of the values of the struct in our main, it is correct. However, when we pass that pointer to another function, and try to access a value, it prints out an incorrect value. It looks like that value is an address.
These calls is in our main:
struct temp * x = doThis();
printf("x->var1 = %d\n", x->var1);
doThat(&x);
In doThat, we print out:
void doThat(void * x)
{
struct temp * x2 = (struct temp *) x;
printf("x2->var1 %d", x2->var1);
}
The doThis function returns a void pointer and the doThat function takes in a void pointer as a parameter.
Upvotes: 0
Views: 337
Reputation: 14695
In doThat
you are casting x to be a struct temp*
, but you pass in a struct temp**
.
You can see a similar result in this: running code.
Changing from:
struct temp * x2 = (struct temp *) x;
printf("x2->var1 %d", x2->var1);
To:
struct temp ** x2 = (struct temp **) x;
printf("(*x2)->var1 %d", (*x2)->var1);
Will fix this. Alternatively, don't pass a pointer to a pointer by changing from:
doThat(&x);
To:
doThat(x); /* <= Note: Don't take the address of x here! */
Upvotes: 8