strcpy doesnot work
Nov 3, 2022 at 2:00pm UTC
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.
Nov 3, 2022 at 2:20pm UTC
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:
or
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 Nov 3, 2022 at 2:27pm UTC
Nov 3, 2022 at 2:24pm UTC
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 Nov 3, 2022 at 2:25pm UTC
Nov 4, 2022 at 4:54am UTC
Get it.
Thanks for your help.
Topic archived. No new replies allowed.