I'm trying to figure out the correct syntax in this situation:
- Assign double pointer to an object
- Get the original address of that double pointer back
Here's a code example:
typedef struct obj2{
obj1 **ptr;
} obj2;
void func(obj1 **dbl)
{
obj2 *tmp = malloc(sizeof(obj2));
printf("before; dbl address is %p\n", (void*)&dbl); // 0x7fff6a1362a0
tmp->ptr = dbl;
// here; trying to print the same address as the first printf
printf("after; dbl address is %p\n", (void*)(tmp->ptr)); // 0x7fff6a136280
}
What am I doing wrong?
EDIT:
The use case for this is so I can use dbl elsewhere in the codebase, so the ultimate goal here is just to be able to correctly pass around a double pointer.
CodePudding user response:
&dbl is the address of the parameter dbl which is a local variable.
tmp->ptr = dbl;
Assigns the tmp->ptr with the value dbl holds, not the address of the variable dbl. Those addresses most likely to be different inless you assign dbl with &dbl (it makes no sense at all).
CodePudding user response:
In this statement
tmp->ptr = dbl;
you are not assigning the address of the pointer db1 to the object tmp->ptr. You are assigning the value stored in the pointer.
So these two calls of printf output different values
printf("before; dbl address is %p\n", (void*)&dbl); // 0x7fff6a1362a0
// here; trying to print the same address as the first printf
printf("after; dbl address is %p\n", (void*)(tmp->ptr)); // 0x7fff6a136280
You should change the first call of printf the following way
printf("before; dbl address is %p\n", (void*)dbl);
