Reputation: 355
When is it appropriate to have a double pointer like in Func1 vs just a pointer in Func2? Would these essentially be the same thing?
void Func1(char **A)
{
}
void Func2(char *B)
{
}
int main(void)
{
char *x;
char y;
Func1(&x);
Func2(&y);
}
Upvotes: 0
Views: 51
Reputation: 5706
It really depends on the data type you want to pass, and what you want to do with it.
Consider that when you pass something by value (which is the default), you are making a copy of it, so if you change it inside the function you won't see the changes outside of it (in the caller function). Instead, if you pass it by pointer, you have the possibility to make those changes persistent (that is, even after you leave the function you will see the changes on the called object, because through the pointer you modify the original variable, not just a copy).
In your example, if you want to modify a char
like y
you can pass it to Func2
. The changes to y
will be persistent, but the changes to B
(which is a char*
) will disappear as soon as you leave the function. Instead, if you want to modify not only the pointed char
, but also the pointer itself, you have to pass the pointer by pointer - that is, you want to use a function like Func1
. Func1
can, in other words, permanently modify x
.
To summarize it:
B
, which is a char*
) can permanently modify a value (like y
, which is char
)A
, which is a char**
) can permanently modify a pointer (like x
, which is a char*
)Upvotes: 1