如何更改传递的参数变量的值? [英] how to change value of variable passed as argument?

查看:116
本文介绍了如何更改传递的参数变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何改变在C参数传递变量的值?
我试了一下:

how to change value of variable passed as argument in C? I tried it:

void foo(char * foo, int baa)
    {
        if(baa) 
        {
            foo = "ab";
        }
        else 
        {
            foo = "cb";
        }
    }

和调用:

char * x = "baa";
foo(x, 1);
printf("%s\n", x);

但它打印为什么?
先谢谢了。

but it prints baa why? thanks in advance.

推荐答案

你想改变其中的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).

所以富()将被改写为:

void foo(char **foo /* changed */, int baa)
{
   if(baa) 
   {
      *foo = "ab"; /* changed */
   }
   else 
   {
      *foo = "cb"; /* changed */
   }
}

打电话时

现在富(),你会传递的指针 X 使用地址运算符(&安培;

Now when calling foo(), you'll pass a pointer to x using the address-of operator (&):

foo(&x, 1);

之所以你不正确片断输出是因为你只是分配一个新值的本地的变量的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆