C语言 如何从被调用函数更改调用函数中的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3377158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:02:50  来源:igfitidea点击:

How to change a variable in a calling function from a called function?

c

提问by kaka

How should the try()function be modified (and it's call) to get the output as 11 from the program below?

应如何try()修改该函数(及其调用)以从下面的程序中获得 11 的输出?

#include <stdio.h>

/* declare try() here */

int main(void)
{
    int x = 10;
    try();              /* Call can change */
    printf("%d\n", x);
    return 0;
}

void try()              /* Signature can change */
{
    /* how to change x here?? */
}

回答by Jeff Mercado

To change the value of xfrom within a function, have try()take a pointer to the variable and change it there.

要从x函数内部更改 的值,请try()获取指向变量的指针并在那里更改它。

e.g.,

例如,

void try(int *x)
{
    *x = 11;
}

int main()
{
    int x = 10;
    try(&x);
    printf("%d",x);
    return 0;
}

回答by Merlyn Morgan-Graham

The other answers are correct. The only way to truly change a variable inside another function is to pass it via pointer. Jeff M's example is the best, here.

其他答案都是正确的。真正改变另一个函数内的变量的唯一方法是通过指针传递它。Jeff M 的例子是最好的,在这里。

If it doesn't really have to be that exact same variable, you can return the value from that function, and re-assign it to the variable, ala:

如果它实际上不必是完全相同的变量,则可以从该函数返回值,然后将其重新分配给变量 ala:

int try(int x)
{
  x = x + 1;
  return x;
}

int main()
{
  int x = 10;
  x = try(x);
  printf("%d",x);
  return 0;
}

Another option is to make it global (but don't do this very often - it is extremely messy!):

另一种选择是将其设为全局(但不要经常这样做 - 它非常混乱!):

int x;

void try()
{
  x = 5;
}

int main()
{
  x = 10;
  try();
  printf("%d",x);
  return 0;
}

回答by Ed S.

You need to pass a pointer to the memory location (a copy of the original pointer). Otherwise you are just modifying a copy of the original value which is gone when the function exits.

您需要传递一个指向内存位置的指针(原始指针的副本)。否则,您只是在修改函数退出时消失的原始值的副本。

void Try( int *x );

int main( void )
{
    int x = 10;
    Try( &x );
    /* ... */
}

void Try( int *x )
{
    *x = 11;
}