在我的代码中按引用调用和按值调用之间感到困惑

时间:2019-05-02 08:32:42

标签: c pass-by-reference call-by-value

今年刚在我的uni中开始C语言,我对函数调用是引用还是值感到困惑。

我在主函数中创建了一个空数组freq_array,并在调用函数频率时将其作为参数传递。因此,既然在func调用之后,空数组现在将包含值,那么这是否被视为按引用调用?我在其他引用引用的网站上使用指针进行了阅读,因此我有些困惑。谢谢。

 void frequency(int[]);    //prototype

 frequency(freq_array); //func call

 void frequency(int fr[arraysize]) //arraysize = 18
 {
       int n;

       for (n=0; n<10; n++)
       {
        fr[n]= 100 * (n + 1);   //goes from 100Hz - 1000Hz
       }

        for (n=10; n<18; n++)       //goes from 2000Hz - 9000Hz
       {
         fr[n]= 1000 * (n - 8); 
       }

     }

2 个答案:

答案 0 :(得分:4)

理论上,C仅具有“按值传递”的功能。但是,当您将数组用作函数的参数时,会将数组调整(“衰减”)为指向第一个元素的指针。

因此,void frequency(int fr[arraysize])完全等同于void frequency(int* fr)。编译器将“在行内”替换为前者。

因此,您可以将其视为通过引用传递的数组,但将指针本身指向第一个元素,即通过值传递

答案 1 :(得分:2)

对于参数,不能仅将指针传递给数组。当编译器看到参数int fr[arraysize]时,它将被视为int *fr

拨打电话时

frequency(freq_array);

数组衰减指向其第一个元素的指针。上面的通话等于

frequency(&freq_array[0]);

并且C根本没有通过引用通过。指针将按值传递。

但是 使用指针,您可以模拟通过引用传递。例如

void emulate_pass_by_reference(int *a)
{
    *a = 10;  // Use dereference to access the memory that the pointer a is pointing to
}

int main(void)
{
    int b = 5;

    printf("Before call: b = %d\n", b);  // Will print that b is 5

    emulate_pass_by_reference(&b);  // Pass a pointer to the variable b

    printf("After call: b = %d\n", b);  // Will print that b is 10
}

现在,重要的一点是要知道指针本身(&b)将按值传递。