Why does name
misbehave in the following C++ code?
string name = "ab"+'c';
How would the equivalent code behave in Java/C#?
Try
std::string name = "ab" "c";
or
std::string name = std::string("ab") + c;
In C++, "ab" is not a std::string
, but rather a pointer to a string of chars. When you add an integral value to a pointer, you get a new pointer that points farther down the string:
char *foo = "012345678910121416182022242628303234";
std::string name = foo + ' ';
name
gets set to "3234", since the integer value of ' ' is 32 and 32 characters past the begining of foo is four characters before the end of the string. If the string was shorter, you'd be trying to access something in undefined memory territory.
The solution to this is to make a std:string out of the character array. std:strings let you append characters to them as expected:
std::string foo = "012345678910121416182022242628303234";
std::string name = foo + ' ';
name
gets set to "012345678910121416182022242628303234 "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With