简体   繁体   English

C-一个功能的多个“输出”

[英]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. 如果我在foo函数中打印值,它将显示正确的值。

But if I try to print them in main, I get nonsense results (0 and 1, respectively). 但是,如果我尝试将它们打印在main中,则会得到无意义的结果(分别为0和1)。

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: 您需要将foo方法更改为采用指针:

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

Then your call to foo must change to: 然后,您对foo的调用必须更改为:

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. 这基本上说:将地址“ a”和“ b”传递给函数foo,因此它具有更改其值的能力。

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. 您之前的代码只是向foo中发送了“ a”和“ b”的副本,因此对foo所做的更改对原始的两个变量没有影响。

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. foo(&a,&b); //将地址传递给函数。

void foo(int *a, int *b)//accessing value at that address void foo(int * a,int * b)//访问该地址的值

The above process is called 'call by reference'. 上面的过程称为“按引用调用”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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