如何更改作为参数传递的变量的值? [英] How to change value of variable passed as argument?
问题描述
如何更改在 C 中作为参数传递的变量的值?我试过这个:
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";
}
}
并调用:
char *x = "baa";
foo(x, 1);
printf("%s
", x);
但它打印 baa
为什么?提前致谢.
but it prints baa
why?
thanks in advance.
推荐答案
您想要更改 char*
指向的位置,因此您需要在 foo()
带有一级间接;一个 char**
(指向 char
指针的指针).
You're wanting to change where a char*
points, therefore you're going to need to accept an argument in foo()
with one more level of indirection; a char**
(pointer to a char
pointer).
因此 foo()
将被改写为:
void foo(char **foo /* changed */, int baa)
{
if(baa)
{
*foo = "ab"; /* changed */
}
else
{
*foo = "cb"; /* changed */
}
}
现在,当调用 foo()
时,您将使用地址运算符 (&
):
Now when calling foo()
, you'll pass a pointer to x
using the address-of operator (&
):
foo(&x, 1);
您的错误代码段打印 baa
的原因是因为您只是为 local 变量 char *foo
分配了一个新值,与 x
无关.因此 x
的值永远不会被修改.
The reason why your incorrect snippet prints baa
is because you're simply assigning a new value to the local variable char *foo
, which is unrelated to x
. Therefore the value of x
is never modified.
这篇关于如何更改作为参数传递的变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!