简体   繁体   中英

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.

It is "both":

The pointer is passed by value, the array "by reference".

C Standard draft, N1256:

6.5.2.2 Function calls
...
4 An argument may be an expression of any object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.
...

I put "both" and "by reference" in quotes, because there are no references in C. A pointer is not a reference, but when used to "pass an array" to a function, it is roughly comparable, in the sense that if the function modifies the array, the changes are visible to the caller. I think this helps understanding what happens here.
We say that an array decays to a pointer, when passed to a function. "Decay" because the pointer looses some information, namely the length of the array. So saying this is similar to "pass by reference" is meant only from an application point of view.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM