Ioan Valentin Voiculescu Ioan Valentin Voiculescu - 1 month ago 17
C Question

How to pass a vector to a function by value in C

I want to pass a vector to a function by value (not by reference). After exectuting the code arr[1], arr[2] and arr[3] are equal 0. What arguments should the fuction

getAvarage
have to not modifey vector
arr
.

#include <stdio.h>
#include <stdlib.h>
double getAverage(int v[]);
int main()
{
int arr[4], i;
for (i = 0 ; i < 4 ; i++){
printf("arr[%d]=", i);
scanf("%d", &arr[i]);
}
printf("avrg=%lf", getAverage(arr));
printf("\n%d %d %d", arr[1], arr[2], arr[3]);
return 0;
}

double getAverage(int v[])
{

int i;
double avg;
double sum = 0;
for (i = 0; i < 4; ++i) {
sum += v[i];
v[i] = 0;
}
avg = sum / 4;
return avg;
}

Answer

As covered by iharob, arrays decay to a pointer to their first element when passed to a function. This is a convenience feature. There are a few similar cases - functions decay to a pointer to the function when passed, almost anything decays to a boolean in a conditional statement. It's just a case of learning these as you go.

There is a solution of sorts to passing an array by value. An instance of a struct will be passed by value, so putting the array in a struct will achieve the desired result.

struct demo
{
  int some_array[4];
};

void i_cant_change_it(struct demo x)
{
  x.some_array[0] = 42;
}

This is because the struct instance, fortunately, doesn't decay to a pointer when passed to a function. If you want to be able to mutate the instance, such that the caller can see the change, the prototype looks like

void i_might_change_it(struct demo *);