Why I can not change the content the char* points to?
For example:
int main(int argc, char * argv[]) {
char *a = NULL; // now a = NULL
b(a);
// but now a points to NULL again! Why?
}
void b(char *argv[], char* c) {
// now a is passed in
c = *argv[3];
// now a actually points to the start of char array pointed to by argv[3]
}
From the output, I see the *a is passed to the function. Then inside the function b, it actually pointed to the expected char[ ]. But when returned from b, a became NULL again. Why? And how can a points to expected content after return from b? Thank you!
C passes everything by value, including pointers. Function parameters are similar to local variables that acquire their initial value from the caller. Once you are inside the function, the value of the parameter can be changed freely without influencing the values passed by the caller.
C's way of passing modifiable stuff into a function is passing pointers. If you want to modify a value of some type T
, you pass a pointer to T
; if you want to modify a pointer to T
, you must pass a pointer to a pointer to T
, and so on. In other words, the level of indirection must be higher by one than that of the value being changed.
How does this apply to your case? Your function b
needs to modify a pointer to char
, hence it needs to take a pointer to a pointer to a char, like this:
void b(char *argv[], char **ppc) {
...
}
Inside the function you modify the pointer to which ppc
points by dereferencing ppc
once:
*ppc = argv[3]; // No asterisk here in front of `argv`
Of course calling b
from the main
needs to take the address of a
, like this:
b(argv, &a);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments