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?
CodePudding user response:
In this call
strcpy(name1, name2);
you are trying to change the string literal pointed to by the pointer name1.
char *name1 = "Allan";
Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
As for this call
strcpy(name2, name1);
then there are overwritten elements of a character array declared like
char name2[] = "Marco";
CodePudding user response:
All literal strings in C are really null-terminated char arrays, and your pointer name1 is pointing to the first element of such an array.
The problem is that the array of a literal string is not allowed to be modified, it's essentially read-only. Attempting to modify a literal string leads to undefined behavior.
That's why it's recommended to use const char * to point to literal strings.
Another important note: The variable name2 is not a pointer, it's an actual array. It can decay to a pointer (to its first element).
