I'll try to explain it here.
Say you have two strings, str1 and str2 declared as char * and you have allocated memory for them and whatnot.
str1 = str2; What would happen here is str1 and str2 would be pointing to the same value. If you changed element 2 of str1 you'd notice you also changed element 2 of str2.
strcpy(str1,str2); Here str1 gets the value pointed to by str2, but stays at it's current address. This way to you get two independant copies of the same data. Edit one and the other doesn't change.
The first syntax, str1 = str2, is also dangerous if you have allocated memory for str1 because the pointer to that memory has not been lost. Do this in a function that is called often and all of a sudden you have a nice memory leak.
An dirty example of real code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str1 = new char[7];
printf("This is a string addr: %d\n", (int) str1);
str1 = "1234567";
printf("This is a string addr: %d\n", (int) str1);
delete str1;
return 0;
}
Results:
This is a string addr: 134520912
This is a string addr: 134514303
Segmentation fault
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str1 = new char[7];
printf("This is a string addr: %d\n", (int) str1);
strcpy(str1,"1234567");
printf("This is a string addr: %d\n", (int) str1);
delete str1;
return 0;
}
Results:
This is a string addr: 134520912
This is a string addr: 134520912
Conclusion:
As you can see here, in the first example the address pointed to by str1 changed after the assignment. So the memory allocated was lost. Then when you go to delete str1, it segfaults.
In the 2nd example the address pointed to does not change, and there is no seg fault.
In short, use strcpy.