0
char *pt = "hello";
std::string str = "hello";

Does str also end with '/0' (is null terminated)?

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
jiafu
  • 6,338
  • 12
  • 49
  • 73
  • maybe? `str.data()` will give you null terminated c string, aside from that you don't really care. – yngccc Nov 28 '13 at 00:51
  • 5
    This question doesn't quite make sense as-is. `std::string` is neither an array nor a pointer, it's a class. How would you define what it "ends with"? –  Nov 28 '13 at 00:51
  • @yngum Also `&str[0]` and `str.c_str()`. –  Nov 28 '13 at 00:52
  • The accepted answer of that question doesn't state that it must be null terminated (or even contiguous?!), but neither here or there do we see quotes from the C++ spec. – Prashant Kumar Nov 28 '13 at 00:57

3 Answers3

3

It is implementation defined whether or not std::string is null-terminated.

The actual contents of str after its definition:

std::string str = "hello";

are characters 'h', 'e', 'l', 'l', 'o' and its size is equal only to 5 characters.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • While this is true, the standard also requires that the underlying controlled sequence be zero terminated when you access it via either `c_str`, `data` or `operator[]` member functions. – Praetorian Nov 28 '13 at 01:04
  • do you make sure that str isn't end with '\o' – jiafu Nov 28 '13 at 03:04
2

The buffer manged by str MAY be null terminated, but not necessarily.

Shoe
  • 74,840
  • 36
  • 166
  • 272
Bukes
  • 3,668
  • 1
  • 18
  • 20
0

str.c_str() will provide you a const char*, which pointed to a null-terminated, contiguous buffer (like your "hello" string literal was).

But be aware of using &str[0] because it's not guaranteed that this points to a contiguous buffer, neither that this buffer is null-terminated.

Joe
  • 3,090
  • 6
  • 37
  • 55