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

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

Solution 1:

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

Solution 2:

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

Solution 3:

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