I have char* that I have defined in the main function. To my understanding, when passing around a pointer and assigning it a value anywhere, the value that the pointer points to is changed universally. But how come it doesn’t behave like this here:
#include <stdio.h>
void idk(char *str) {
printf("1.idk: %s\n", str);
str = "hello world";
printf("2.idk: %s\n", str);
}
int main() {
char *str = "init value";
printf("1.main: %s\n", str);
idk(str);
printf("2.main: %s\n", str);
return 0;
}
Output:
1.main: init value
1.idk: init value
2.idk: hello world
2.main: init value // why is this not "hello world"?
>Solution :
Because you changed the pointer, not the value it points to.
Consider this code.
void idk(int num) {
num = 42;
}
You wouldn’t expect this to change the value outside the function. num is a copy of the value. Same thing with a pointer. A pointer is just a number. You changed the number, not the value it points at.
If you want to change the number, you pass in a pointer to it and dereference it to access its value.
void idk(int *num) {
*num = 42;
}
Same thing, we need a pointer to the char *. A char **, a pointer to a pointer, a "double pointer".
First, make sure str is initialized, using an uninitialized value is undefined behavior. We’ll use strdup to make sure the value is not constant (not strictly necessary, but it avoids having to deal with constant pointers vs pointers to constants).
Then we pass in a pointer to the char *, a char **.
Inside the function, we dereference the char ** to change what it points at.
#include <stdio.h>
#include <string.h>
void idk(char **str) {
printf("1.idk: %s\n", *str);
*str = "hello world";
printf("2.idk: %s\n", *str);
}
int main() {
// Make sure str is initialized and not constant.
char *str = strdup("testing 123");
printf("1.main: %s\n", str);
// Pass in a pointer to the char *
idk(&str);
printf("2.main: %s\n", str);
return 0;
}