开发者

How to change a variable in a calling function from a called function? [duplicate]

This question already has answers here: Passing by reference in C 开发者_如何学JAVA (19 answers) What's the difference between passing by reference vs. passing by value? (18 answers) Closed 4 years ago.

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

#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?? */
}


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

e.g.,

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

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


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.

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:

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;
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜