简体   繁体   中英

C - multiple “outputs" from a function

I must be doing something monumentally stupid here but I can't figure out what. If I printf the values within the foo function, it displays the correct values.

But if I try to print them in main, I get nonsense results (0 and 1, respectively).

void foo(int a, int b){

    a = 1;
    b = 2;

}

int main(void){

    int a;
    int b;

    foo(a, b);

    printf(“%i \n”, a);
    printf(“%i \n”, b);

}

You need to change your foo method to take pointers:

void foo(int *a, int *b)
{
   *a = 1;
   *b = 2;
}

Then your call to foo must change to:

foo(&a, &b);

This basically says: Pass the address of 'a' and 'b' to the function foo, so it has the ability to change their values.

Your previous code just sent a copy of 'a' and 'b' into foo, so the change made in foo had no effect on your original two variables.

In your program you are trying to change the local variables in your function without passing their adresses.It may give you error in your code.If you pass the addresses to the function you can change the values of variables.

foo(&a, &b);//Passing addresses to the function.

void foo(int *a, int *b)//accessing value at that address

The above process is called 'call by reference'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM