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 ?

2
  • What are you trying to do here: Why do you need to use strings instead of just character arrays? Commented Jul 28, 2013 at 8: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 Commented Jul 28, 2013 at 8:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

so something like char w[]="qwe\0""0uqwe"; printf("%s\n%s",w,w+4); is wrong ?
char w[]="qwe\0""0uqwe" casts a const char* to char[]. That's wrong.
The string capacity isn't completely outside the scope of the spec: you're guaranteed that capacity >= size.
"How much additional space is ...". Better?
So is size here size of "qwe" or size of "qwe\0""0uqwe" ?
|
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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.