J
jl_post
Hi,
I have a couple of questions about the std::string class that I
haven't been able to answer by looking in the documentation.
Basically, if I do this:
std::string str = "abc";
char s[4];
memcpy(s, str.c_str(), 4);
then the following will hold true:
s[0] == 'a'
s[1] == 'b'
s[2] == 'c'
s[3] == '\0'
(s[3] is a null character because ::c_str() guarantees that its return
string is null-terminated.)
But if I were to end my str variable with null bytes, like this:
std::string str("a\0\0", 3);
char s[4];
memcpy(s, str.c_str(), 4);
then I figure that the following two expressions are true:
s[0] == 'a'
s[1] == '\0'
But what about these expressions?:
s[2] == '\0'
s[3] == '\0'
We know that s[1] HAS to be a null character (because ::c_str()
guarantees that its return string will be NULL-terminated).
So my questions (which pertain to the second example) are:
1. Since the second character is already a null byte, is ::c_str()
still guaranteed to return '\0' as its third character (since that's
what was passed in to the std::string constructor)? (Basically, I'm
asking if s[2] is guaranteed to hold '\0'.)
2. Since str already ends in a null byte (two of them, actually)
is ::c_str() still guaranteed to return a string with an extra null
byte at the end (like it did in the first example to the "abc"
string)? (Basically, I'm asking if s[3] is guaranteed to hold '\0'.)
Thanks in advance for any input.
-- Jean-Luc
I have a couple of questions about the std::string class that I
haven't been able to answer by looking in the documentation.
Basically, if I do this:
std::string str = "abc";
char s[4];
memcpy(s, str.c_str(), 4);
then the following will hold true:
s[0] == 'a'
s[1] == 'b'
s[2] == 'c'
s[3] == '\0'
(s[3] is a null character because ::c_str() guarantees that its return
string is null-terminated.)
But if I were to end my str variable with null bytes, like this:
std::string str("a\0\0", 3);
char s[4];
memcpy(s, str.c_str(), 4);
then I figure that the following two expressions are true:
s[0] == 'a'
s[1] == '\0'
But what about these expressions?:
s[2] == '\0'
s[3] == '\0'
We know that s[1] HAS to be a null character (because ::c_str()
guarantees that its return string will be NULL-terminated).
So my questions (which pertain to the second example) are:
1. Since the second character is already a null byte, is ::c_str()
still guaranteed to return '\0' as its third character (since that's
what was passed in to the std::string constructor)? (Basically, I'm
asking if s[2] is guaranteed to hold '\0'.)
2. Since str already ends in a null byte (two of them, actually)
is ::c_str() still guaranteed to return a string with an extra null
byte at the end (like it did in the first example to the "abc"
string)? (Basically, I'm asking if s[3] is guaranteed to hold '\0'.)
Thanks in advance for any input.
-- Jean-Luc