As the others noted, the only way in C to pass an array by value is to use a struct
with a fixed size array. But this is not a good idea, because the array size will be hardcoded into the struct
definition.
However, you really should not try to pass arrays by value. Instead, what you should do is simply to declare your pointer parameter as const
, like this:
int sum(size_t count, const int* array) {
While this does not pass the array by value, it clarifies the intent not to change the array, i. e. you can now treat sum()
as if you were passing the array by value.
If your function does indeed not change the array (like your sum()
function), using a const
pointer comes for free, copying the array to pass it by value would just waste time.
If your function really wants to change a private copy, do so explicitely within the function. If the array won't get too large, you can simply allocate it on the stack, like so:
int doSomethingWithPrivateCopy(size_t count, const int* array) {
int mutableCopy[count];
memcpy(mutableCopy, array, sizeof(mutableCopy));
//Now do anything you like with the data in mutable copy.
}