Search code examples
carraysdynamic-allocation

Is Passing a Dynamically Allocated Array to a Function in C an Instance of Pass-by-value or Pass-by-reference?


To demonstrate, here is an example code recreating the instance of passing a dynamically allocated array to a function.

#include <stdio.h>
#include <stdlib.h>
void fx1(int* arr) {/* code here */ }
int main() {
    int *arr = (int *) malloc(sizeof(int) * 10);
    fx1(arr);
    free(arr);
    return 0;
}

In the example, I first create a dynamically allocated array, arr. Then, I pass it to a function called fx1. The title is exactly my question. Is passing a dynamically allocated array to a function in C an instance of pass-by-value or pass-by-reference? I would also like a reference/s (book, documentation, etc) if you have an answer for this.


Solution

  • In C, everything is passed by value. In your concrete example arr is. You don't have references like in C++ or Java.

    Let's take a C++ example:

    void foo(int& i) {
        ++i;
    }
    
    int main() {
        int i = 1;
    
        foo();
    }
    

    Here, true references are used. i is passed by reference and foo modifies i over a reference to i. No "copying by value" takes place.

    OTOH, in C, you don't have references. You can only write something like

    void foo(int* i) {
        ++*i;
    }
    
    int main() {
        int i = 1;
    
        foo(&i);
    }
    

    To pass something "by reference"1 in C, you need to pass a pointer to it, just like you did. The pointer itsself is passed by value but it refers to a memory area (here i) modifiable by both the function and the allocator.

    In the end, if you want to pass something "by reference" in C, copying by value is always involved. Not so in C++.

    Quoting from K&R, 1.8 Arguments - Call by Value:

    In C, all function arguments are passed by value.''


    1 Note that this is within double quotes. C doesn't have "pass-by-reference." Period.