Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
7  
One invokes undefined behaviour and the other doesn't. –  Kilian Foth Nov 19 '13 at 13:14
1  
string::operator[] certainly IS a function call. It uses syntactical sugar to look like array access, but it is a function. –  John Gaughan Nov 20 '13 at 2:28
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
    
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 ? –  clickstefan 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." –  clickstefan 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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