3

What are the differences between string.c_str() and &string[0]?

Regarding performance my guess is that &string[0] is a little faster than string.c_str() as it doesn't require a function call.

Regarding safety and stability common sense tells me that string.c_str() should have some checks implemented, but I don't know, that's why I'm asking.

  • 7
    One invokes undefined behaviour and the other doesn't. – Kilian Foth Nov 19 '13 at 13:14
  • 4
    string::operator[] certainly IS a function call. It uses syntactical sugar to look like array access, but it is a function. – user22815 Nov 20 '13 at 2:28
8

In C++98 there is no guarantee that the internal array is null terminated; in other words string.data()[string.size()] results in undefined behavior. The implementation will then reallocate the array with the null termination when c_str() is called but can leave the null terminator off when it isn't.

This also means that &string[0] is not guaranteed to be null terminated (it is essentially a detour to data())

In C++11 the null termination guarantee is specified so string.data()==string.c_str() is always valid.

  • so in C++98 &string[0] could be <> string.c_str() and result in undefined behavior when string.size() = 0 and in C++11 &string[0] == string.c_str() always ? – Stefan Rogin Nov 19 '13 at 13:57
  • I didn't understand this part: "The implementation will then reallocate the array with the null termination when c_str() is called but can leave the null terminator off when it isn't." – Stefan Rogin Nov 19 '13 at 14:00
  • 1
    @clickstefan the C++98 standard allows strings to share the internal array and have other strings point to a substring (which can't be null terminated), when that substring needs the `c_str()´ it will need to allocate it's own copy and add the terminator. and since it just allocated the array it will then be able to use that as its internal array. – ratchet freak Nov 19 '13 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.