-1

I'm a new in learning C and I do not completely understand how 'void' function can modify some variables. For example

void copyString (char  to[], char  from[])
{
int  i;
for ( i = 0;  from[i] != '\0';  ++i )
to[i] = from[i];
to[i] = '\0';
}

Why can I use modified version of 'to' string? Shouldn't it be modified only in a copyString's stack and not for the whole programm or I misunderstand something? I understand that 'to' is a formal parameter, but I thought that it shoul change the value only inside the function because it is local to that function. Please explain where the problem in my logic?

  • 4
    What looks like an array is really a pointer which the array decayed to at call site. You are modifying the array pointed to by that pointer rather than a copy. Arrays in C are passed by reference. – Tanveer Badar Sep 01 '21 at 04:46
  • You need to post the calling code, but I would hazard a guess that `to` is (at least) one character shorter than you need. – Ken Y-N Sep 01 '21 at 04:52
  • Please read http://c-faq.com/aryptr/aryptrparam.html . – Karl Knechtel Sep 01 '21 at 05:00

1 Answers1

1

What seemingly looks like pass-by-value turns into pass-by-reference due to array decay. Array decay is the loss of type and dimension of the array when passed to a function as a value. So instead of passing the array, pointer to the first address of the array is passed.

So what looks like this:

void copyString (char  to[], char  from[])

The Compiler actually looks at it like this:

void copyString (char  *to, char  *from)

You are modifying the values pointed by the pointer rather than a copy in the stack.

More information on array decay can found here.

Thilak
  • 70
  • 10