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?
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.