0

Afaik, calling .c_str() on a string object should give me a pointer to a null terminated char array while .size() doesn't include the null terminator.

Does it stand to reason then that when I want to copy this string into a char array I can safely set the copy length to .size() + 1?

Or are there any caveats I should be aware of?

I'm working with c++11 on vs2013

user81993
  • 6,167
  • 6
  • 32
  • 64
  • 3
    Yes, your reasoning is correct. – Michael Aaron Safyan Feb 18 '16 at 04:57
  • 3
    There are several duplicates of this question, but basically, yes, the C++11 standard requires that that null character is there. The standard explicitly forbids dereferencing the iterator `std::string::end()` but that is all. – Chris Beck Feb 18 '16 at 04:58
  • @ChrisBeck, The iterator thing is funny because you [are allowed](http://en.cppreference.com/w/cpp/string/basic_string/operator_at) to say `str[str.size()]`. – chris Feb 18 '16 at 04:59
  • 1
    One thing to watch out for is `std::string` is capable of holding embedded nulll characters. Hence, `string::size()` and `strlen(string::c_str())` may be different. – R Sahu Feb 18 '16 at 05:02
  • @ChrisBeck I don't think this is a duplicate of that. His first sentence confirms that he knows that answer, his question is about how to allocate a C-style string that will hold a copy of the string. – Barmar Feb 18 '16 at 05:43
  • Yeah maybe its not an exact duplicate of the question. But, I guess the meat of his question is about what happens if he copies from a range of the string including `[string.size()]` and if there are any caveats or funny business... I think the answers I linked answer this question? I'm not exactly sure if marking as a dupe is appropriate in cases like that I guess. – Chris Beck Feb 18 '16 at 05:51

0 Answers0