如何在C中正确编写一个通过引用接受参数的函数?

Mel*_*tix 0 c pointers reference

我正在搜索此信息一段时间。在互联网上搜索时,许多站点都说一个Function引用是这样写的:

//Example 1
#include <stdio.h>

void somma (int a, int b, int *c) {
    *c = a + b;
}

int main (void) {
    int a = 4;
    int b = 2;
    int c = 8;

    somma(a, b, &c);

    printf("Risultato somma: %d", c);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但这就是我在学校学到的:

#include <stdio.h>

void somma(int a, int b, int &c) {
    c = a + b;
}

int main(void)
{
    int a = 4;
    int b = 2;
    int c = 8;

    somma(a, b, c);

    printf("Risultato somma: %d", c);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这实际上使我感到困惑,因为如果我尝试编译程序(编写的方式就像我在学校学习的那样),则会遇到编译错误,其中涉及到函数本身:

[ripasso2.c 2019-08-25 21:19:47.684]
ripasso2.c:3:30: error: expected ';', ',' or ')' before '&' token
 void somma(int a, int b, int &c) {
                              ^

[ripasso2.c 2019-08-25 21:19:47.684]
ripasso2.c: In function 'main':
ripasso2.c:13:5: warning: implicit declaration of function 'somma' [-Wimplicit-function-declaration]
     somma(a, b, c);
     ^~~~~
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我把指针弄混了吗?

Mar*_*lli 6

这个:

void somma(int a, int b, int &c) {
Run Code Online (Sandbox Code Playgroud)

不是有效的C语法。这是C ++语法。如果他们在学校以C的身分教给您,那就错了。

编译器会对此产生错误,然后还警告您somma未声明该函数,因为无法正确处理该事实。这实际上只是一个错误。

有效的C声明是第一个:

void somma (int a, int b, int *c) {
Run Code Online (Sandbox Code Playgroud)

如果要编译C ++版本(使用的版本int &c),则必须使用g++,而不是gcc。您可以通过简单的安装sudo apt install g++(假设您使用的是Linux),然后可以像使用一样编译程序gcc