std::string von char* initialisieren - terminierung
-
Hallo,
kurze klarstellung. Die Referenz sagt
string ( const char * s );Content is initialized to a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of the caracter sequence is determined by the first occurrence of a null character (as determined by traits.length(s)). This version can be used to initialize a string object using a string literal constant.
Das heißt wenn mein char[] so aussieht:
char cstr[6] = {'a','b',0x0,'c','d', 0x0}; std::string str(cstr);Dann ist der Inhalt von str = "ab" ?
habe ich das korrekt verstanden?
-
Ja, das hast du richtig verstanden. Bei C-Strings wird der Teil nach dem ersten Auftreten der Nullterminierung immer ignoriert, das gilt auch für die C-Funktionen, die mit
strbeginnen.
-
Exakt.
In C++ sind C-String (Char*) generell null-terminiert. Wenn du sowas machst wie const char* ab = "AB"; erstellt der Compiler im Grunde etwas wie: const char[] ab = { 'A', 'B', '\0' };
('\0' == 0x0)
-
Danke, alles klar!