I have came across this problem when using pointer to pointer to a char:
void setmemory(char** p, int num)
{
*p=(char*)malloc(num);
}
void test(void)
You are only setting the local variable *p here. Remember you are getting a pointer to data, not a pointer-to-pointer-to-data.
Think of it like this:
First case:
int a;
foo(a); // Passes a
void foo(int b)
{
b = 4; // This only changes local variable, has no effect really
}
Second case:
int a;
foo(&a); // Passes *a
void foo(int *b)
{
*b = 4; // This changes the contents of a. As you can see we have not changed the original pointer!
b = 4; // This changes our local copy of the pointer, not the pointer itself, like in the first case!
}
Third case
int *ptr;
foo(&ptr); // Passes **ptr
void foo(int **b)
{
**b = 4; // This changes the data of the passed pointer
*b = 4; // This changes the passed pointer itself, i.e. it changes ptr. This is what test() is doing, the behavior you are looking for!
b = 4; // This changes our local copy of a variable, just like the first case!
}