First of all the first program has undefined behaviour.
Array foo
is defined as having only one element (the terminating zero of the "empty" string literal)
char foo[] = "";
However you are going to copy string "Testing" in the array.
copy(foo, bar);
This results in overwritting the memory that does not belong to array foo
.
Array foo
should be enough large to be able to accomodate string "Testing".
For example
char foo[8];
According to the C Standard (6.7.6.3 Function declarators (including prototypes))
7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted
to ‘‘qualified pointer to type’’, where the type qualifiers (if any)
are those specified within the [ and ] of the array type
derivation....
On the other (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array
object has register storage class, the behavior is undefined.
Thus in this function declaration
void copy(char to[], char from[]);
parameters to
and from
are adjusted to pointers. So this function declaration is equivalent to the following function declaration
void copy(char *to, char *from);
and the both declare the same one function.
You may write in the program the both declarations. For example
#include <stdio.h>
void copy(char to[], char from[]);
void copy(char *to, char *from);
void copy(char to[], char from[]) {
int i = 0;
while ((to[i] = from[i]) != '\0') i++;
}
//...
but the definition of the function shall be only one.
And in this function call
copy(foo, bar);
according to the second quote from the Standard arrays foo
and bar
are converted to pointers to their first elements.
As for the function from the second program then function parameters are its local variables. A function deals with copies of its arguments. So any changes of a copy of an argument do not influence on the argument itself.
You can imagine the definition of function arr_alter and its call the following way
arr_alter(test_arr);
//...
void arr_alter( /*char arr[] */) {
char *arr = test_arr;
arr = "Changed";
}
After exiting the function its local variable arr
will be destroyed. Variable test_arr
will not be changed and moreover arrays have no the assignment operator. You can not reassign an array such a way.