There is a program in C:
void bar(char *str) {
str = "ok bye!";
}
int main(int argc, char *argv[]) {
char *str = "hello world!";
bar(str);
printf("%s\n", str);
return EXIT_SUCCESS;
}
However, it says that the value str
in main method would not be effected by the bar method, but why is that? My understanding is that char *str = "hello world!";
this code makes the pointer str
points to the string "hello world". And then bar(str);
makes the str
pointer points to the string "ok bye!". But why the result is still "hello world"?
void bar(char **str_ptr) {
*str_ptr = "ok bye!";
}
The solution is to change the parameter of the bar method to a double pointer, why to do that?