Is String::c_str() No Longer Null-Terminated in C 11?
In C 11, the behavior of string::c_str() has been a matter of debate. Some sources suggest that it may no longer produce a null-terminated string.
However, upon closer examination, it becomes clear that this is not the case. The definition of operator[] in C 11 requires strings to use null-terminated buffers internally. This means that c_str(), which is defined in terms of operator[], must also return a null-terminated string.
Specifically, section 21.4.5 of the C 11 standard states that operator[] must return "a reference to an object of type T with value charT(); the referenced value shall not be modified." This implies that the string must contain a null character at its end.
Additionally, section 21.4.7.1/1 defines c_str() as "A pointer p such that p i == &operator[](i) for each i in [0,size()]." This means that c_str() provides access to the same buffer as operator[], which must be null-terminated.
Therefore, despite initial concerns, string::c_str() is still guaranteed to produce a null-terminated string in C 11.
The above is the detailed content of Here are a few title options, keeping in mind the question format: Direct and Clear: * Is `string::c_str()` Still Null-Terminated in C 11? * Does `string::c_str()` Guarantee Null Termination in C. For more information, please follow other related articles on the PHP Chinese website!