cpass-by-referencecall-by-value

Confused between call by ref and call by value in my code


Just started C this year in my uni and I'm confused whether my function call is by reference or value.

I created an empty array in main called freq_array and this is passed as an argument when the function frequency is called. So since after the func call, the empty array will now contain values, this is considered call by reference? I read in other websites that call by reference uses pointers so I'm slightly confused. Thank you.

 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); 
       }

     }

Solution

  • In theory, C only has "pass by value". However, when you use an array as parameter to a function, it gets adjusted ("decays") into a pointer to the first element.

    Therefore void frequency(int fr[arraysize]) is completely equivalent to void frequency(int* fr). The compiler will replace the former with the latter "behind the lines".

    So you can regard this as the array getting passed by reference, but the pointer itself, pointing at the first element, getting passed by value.