How to change value of variable passed as argument in C?
I tried this:
void foo(char *foo, int baa){
if(baa) {
foo = "ab";
} else {
foo = "cb";
}
}
and call:
char *x = "baa";
foo(x, 1);
printf("%s\n", x);
but it prints baa why?
thanks in advance.
You’re wanting to change where a
char*points, therefore you’re going to need to accept an argument infoo()with one more level of indirection; achar**(pointer to acharpointer).Therefore
foo()would be rewritten as:Now when calling
foo(), you’ll pass a pointer toxusing the address-of operator (&):The reason why your incorrect snippet prints
baais because you’re simply assigning a new value to the local variablechar *foo, which is unrelated tox. Therefore the value ofxis never modified.