Define the following variables:
char *name1 = "Allan";
char name2[] = "Marco";
printf("%s %s\n", name1, name2); // Allan Marco
Then the following code works fine:
strcpy(name2, name1);
printf("%s %s\n", name1, name2); // Allan Allan
But reversing the arguments corrupts the string:
strcpy(name1, name2);
printf("%s %s\n", name1, name2); // Does not work!
Why does this not work? name1
and name2
both evaluate to pointers to the first element of their respective strings, so why does strcpy
discriminate between the two variables? And furthermore, why does it not work?