0

今年刚开始在我的大学学习 C,我很困惑我的函数调用是通过引用还是值。

我在 main 中创建了一个名为 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); 
       }

     }
4

2 回答 2

4

理论上,C只有“传值”。但是,当您使用数组作为函数的参数时,它会被调整(“衰减”)为指向第一个元素的指针。

因此void frequency(int fr[arraysize])完全等价于void frequency(int* fr)。编译器将用后者“在后面”替换前者。

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

于 2019-05-02T08:39:55.983 回答
2

对于参数,您不能只传递数组指针。当编译器看到int fr[arraysize]它会处理的参数是 as 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) 将按值传递。

于 2019-05-02T08:39:25.407 回答