0

From Rules for C++ string literals escape character ,Eli's answer

std::string ("0\0" "0", 3)  // String concatenation 

works because this version of the constructor takes a char array; if you try to just pass "0\0" "0" as a const char*, it will treat it as a C string and only copy everything up until the null character.

Does that mean space isn't alloted for entire string , ie the string after \0 is written on unalloted space ?

Moreover the above question is for c++ string, I observed same behaviour for c strings too . Are c and c++ strings same when I add null char in middle of string during declaration ?

Community
  • 1
  • 1
Zxcv Mnb
  • 733
  • 8
  • 19
  • What are you trying to do here: Why do you need to use strings instead of just character arrays? – hugomg Jul 28 '13 at 08:34
  • There is a set of strings which could be represented as a array of pointers to char[] , but is represented as char[] with \0 separating strings and int[] to store offsets of strings – Zxcv Mnb Jul 28 '13 at 08:41

2 Answers2

2

The char array is copied into the new object. If you don't specify, how long the char array is, C++ will copy until the first null character. How much additional space is allocated is outside the scope of the specification. Like vectors, strings have a capacity that can exceed the amount required to store the string and allows to append characters without relocating the string.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus stops when it reaches the '\0' character.

If you really want to play you need to use the constructor that builds the string from a char array (not a C-String).

STL sequence containers exceed the amount required to store automatically

Example :

int main () {

string s="Elephant";

s[4] ='\0'; //C++ std::string is NOT '\0' terminated
cout<<s<<endl; //Elep ant

string   x("xy\0ab");   // C-String assumed.

cout<<x; //xy
  return 0;
}
P0W
  • 46,614
  • 9
  • 72
  • 119