-1

I wanted to know that while passing an array to a function in c. Is it the copy of array values that get passes or the array address(reference) that gets passed?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

1

When a array is passed as an argument to function it is implicitly decays to a pointes for example

char * foo(char buffer[])
{
printf("sizeof buff= %d",buffer); // here you will get pointer size not original buf because buffer is decay to pointer as char *buffer

}

int main()
{
char buf[10]="hello";
foo(buf);

}

Reason why it decays to pointer is time .It is more costly for copying all the element in the arrays to the calling function parameter. So implicitly it decays to pointer.

Rohini Singh
  • 297
  • 1
  • 14
0

Is it the copy of array values that get passes or the array address(reference) that gets passed?

technically, neither. In C function arguments are always passed by value. In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.

However, just as any other pointer type argument, if, from the called function you alter any value pointed to by the pointer (or, a derived pointer via pointer arithmetic, as long as you stay within the valid range), the actual array element values inside the caller function is also affected.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261