Concat strings, assign to char pointer

Pages: 12
strcpy(a, &str1[0]);
this is not safe. c++ strings are NOT zero terminated in all cases.
you should use memcpy and the length() instead, or use the c_str() method to give you zero terminated data.

&string[index] has several high risk things if you do it. Its usable, but its risky.
- the pointer can change, so if you stored the above in a pointer, it could go invalid without your knowing.
- if you change the length, the string object will be broken.
- if you injected a zero into it, the string object will not acknowledge this.
- it may not be zero terminated, so using c functions on it may not work right

if you want to understand it, try playing with it.
string s = "x";
char *cp = &s[0];
s = "good bye cruel and heartless world, I can take it no longer";
cout << cp << endl; //this may work on some compilers but if you make the above line long enough eventually it will break.
or try this gem:
s = "hello world";
cp[5] = 0;
cout << s; //hmm.

Last edited on
Topic archived. No new replies allowed.
Pages: 12