【问题标题】:Compilation of a simple function in c on linux在linux上用c编译一个简单的函数
【发布时间】:2020-01-09 15:08:44
【问题描述】:

在终端上编译时显示:

    studente@Linux-Mint-19-SO:~$ gcc -c prova.c
    prova.c:4:16: error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token
     void gesoo(int &, int &);
            ^
    prova.c: In function ‘main’:
    prova.c:11:2: warning: implicit declaration of function ‘gesoo’ [-Wimplicit-function- 
   declaration]
      gesoo (a, b);
      ^~~
    prova.c: At top level:
    prova.c:17:16: error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token
     void gesoo(int &a, int &b){

应该产生这个问题的函数是

    void gesoo(int &a, int &b){
        int temp;
        temp=a;
        a=b;
        b=temp;
    }

这是一个简单的交换过程,在 Dev-C++ IDE 上使用时没有问题。

【问题讨论】:

    标签: c linux terminal


    【解决方案1】:

    这是有效的 C++,但不是有效的 C。C 不支持按引用传递,C 中的所有内容都是按值传递。要在 C 中获得相同的功能,您需要按值传递指针:

    void gesoo(int *a, int *b){
        int temp;
        temp = *a;   // The asterisk dereferences the pointer
        *a = *b;
        *b = temp;
    }
    

    你会这样称呼它:

    int a = 3;
    int b = 4;
    gesoo(&a, &b);  // the & means pass the address of that variable
    printf("a = %d, b = %d\n", a, b);  // prints a = 4, b = 3
    

    请注意,这也适用于 C++,但在现代 C++ 中使用原始指针并不是最佳实践。

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多