I got quite confused when I came across char**, is it really necessary to cope with string?
For example:
double strtod(const char *nptr,char **endptr);
If endptr
is not NULL, a pointer to the character that stopped the scan is stored at the location pointed to by endptr
. ---MSDN
This is quite complicated, why not just copy pointer to the character to endptr
? All computations after the call can be achieved by passing the pointer's value to endptr
as I think.
Is char**
really needed?
Imagine there's a type called my_type
, and you have a function called foo()
that needs a pointer to a my_type
so that it can modify it:
void foo(my_type *t);
Now, lets look at how my_type
is actually defined:
typedef char* my_type;
So it doesn't matter if the type is already a pointer. If you want to pass a pointer to a variable of that type, you need its address. So the decomposition of:
my_type *t
would be:
char **t
Whenever you want a pointer to a variable of type char *
, you need a char **
.
Arguments in C are passed by value. If you want the caller of a function to see a change made to an argument passed to a function you need to pass the address of the argument to the function. This is why the char**
is being passed. The caller has a variable of type char*
and passes its address. If it is changed in the function the caller can see that change.
For example:
void set_int(int i) { i = 4; }
/* Caller */
int x = 7;
set_int(x);
/* 'x' is still 7 */
void really_set_int(int* i) { *i = 4; }
/* Caller */
int x = 7;
really_set_int(&x);
/* 'x' is now 4 */
The same behaviour for a variable of type char*
. If a function needs to change what the char*
is pointing to (not its content) it needs the address of the char*
, which is of type char**
.