strcpy doesnot work

Just check the code below:
1
2
3
4
5
char* s1 = "hello";
char* s2 = "world";
cout<<s2<<endl; // world
strcpy(s2, s1);
cout<<s2<<endl; // world 

Why does s2 remain the same after strcpy?
Thanks in advance.
s2 points to read-only memory.

You should actually be using const (modern compilers will at least warn if you don't).

1
2
const char* s1 = "hello";
const char* s2 = "world";

If you did this you would have got a compilation error telling you that you're not allowed to pass a pointer to const as the first argument to strcpy.

What you probably want is:
 
char s2[] = "world";
or
 
char s2[6];

Just make sure it's big enough to hold the string that you're going to store in it (including the null terminator).
Last edited on
In case you're not aware, there is a string class type in the standard library (inside the <string> header) which makes this much easier (and less error prone).

1
2
3
4
5
std::string s1 = "hello";
std::string s2 = "world";
std::cout << s2 << "\n"; // world
s2 = s1;
std::cout << s2 << "\n"; // hello 
Last edited on
Get it.
Thanks for your help.
Topic archived. No new replies allowed.