如何通过值调用和通过引用调用在C中工作?

时间:2009-11-02 03:27:51

标签: c++ c

在C程序中,函数按值调用的方式如何,以及如何通过引用调用,以及如何返回值?

3 个答案:

答案 0 :(得分:11)

按值调用

void foo(int c){
    c=5; //5 is assigned to a copy of c
}

这样称呼:

int c=4;
foo(c);
//c is still 4 here.

通过引用调用:传递指针。引用存在于c ++

void foo(int* c){
    *c=5; //5 is assigned to  c
}

这样称呼:

int c=0;
foo(&c);
//c is 5 here.

返回值

int foo(){
    int c=4;
     return c;//A copy of C is returned
}

通过参数返回

   int foo(int* errcode){

       *errcode = OK;

        return some_calculation
   }

答案 1 :(得分:5)

C语言不支持call-by-reference。

你可以做的是将一个指针(作为参考,但与C ++称之为“引用”不同)传递给你的函数感兴趣的数据,这使你可以做大部分调用的事情-by-reference适合。

答案 2 :(得分:0)

请注意,如果要修改指针,则必须通过引用传递指针。

在此示例中,p仅在堆栈上更改(在函数范围内),并在函数退出时获得旧值:

void do_nothing(char *p)
{
    p = (char *)malloc(100);
}

要修改指针,必须通过引用传递它:

void my_string(char **p)
{
    *p = (char *)malloc(100);
}

和电话:

char *str = NULL;
my_string(&str);
...
free(str);
相关问题