Yes it is true that passing pointers is a way to have functions edit the variables passed to them, but not in the way that you're trying to do it.
When you pass an argument to a function in C (pointer or otherwise), a new variable is created for your function to do what it pleases with, and the value of the argument is put in this new variable. This new "local" variable will be discarded when your function returns.
Where pointers get around this is you can dereference them inside of your functions to edit the value(s) they point to, so the changes will be reflected outside of the function.
Consider the following:
#include <stdio.h>
void bar(int local_foo) {
local_foo = 21;
}
void baz(int *local_foo_ptr) {
*local_foo_ptr = 21;
}
int main() {
int foo = 19;
printf("First: %d\n", foo);
bar(foo);
printf("Second: %d\n", foo);
baz(&foo);
printf("Third: %d\n", foo);
}
A small clarification: you may not have encountered the &
operator before. What it does is gets a pointer the the variable it is applied to. So in
baz(&foo);
what is happening is baz()
is being called, and a pointer to foo
is being passed to it.
Anyways, bar()
fails to make any change to foo
because all it does is store 21
into local_foo
. This does nothing to change foo
in main()
.
However, baz()
is passed a pointer to foo
(which is stored in local_foo_ptr
), and it dereferences this pointer to change the value it points to, which in this case is foo
in main()
. Thus the output of this program is:
First: 19
Second: 19
Third: 21
Now consider your program again, but with the variable names changed to make things easier to understand:
#include <stdio.h>
void idk(char *local_str) {
printf("1.idk: %s\n", local_str);
local_str = "hello world";
printf("2.idk: %s\n", local_str);
}
int main() {
char *str = "init value";
printf("1.main: %s\n", str);
idk(str);
printf("2.main: %s\n", str);
return 0;
}
In idk()
, only local_str
is changed, and str
in main()
is unaffected. Thus after the call to idk()
, str
still points to the string "init value"
, and this is reflected in the output.
One way to get around this is to pass a pointer to str
to idk()
, and dereference that to change str
in main()
. This is usually called using a "double pointer". Here's one way this could be done:
void idk(char **local_str_ptr) {
...
*local_str_ptr = "hello world";
...
}
int main() {
...
idk(&str);
...
}
In this, we generate a pointer to str
and pass that as an argument, thus the function can dereference this pointer and change the value of str
in main()
.
That said, there's more than one way to skin a cat, and this is by no means how it "has to" or "should" be done.