Are C strings (as opposed to std::string) guaranteed to be implemented as arrays? For example, say, I have
char const * str = "abc";
What it boils down to is whether or not str + 4 a legal pointer value (without dereferencing that is). I’m asking this because I dont know if C strings are a special case due to the null character terminating it.
First part of the question
Yes, a string object is of an array type. A character string is a data format and a (character) string object is of a type
arrayofchar.In your example
strpoints to the string literal"abc". Character string literals have the typechar[N+1]whereNis the length of the string (i.e., the number of characters excluding the terminating null character).Some references from Standard and K&R 2nd edition:
C defines a string literal as:
and says (emphasis mine):
K&R 2nd edition says:
and
Second part of the question
Yes, it is a valid pointer. In your case
str + 4is a pointer one past the last element of the array.A valid pointer is a pointer that is either a null pointer or a pointer to a valid object. For an element of an array object, a pointer one past the last element of the array object is also a valid pointer.
Note that for the purpose of the last rule (“the one past element”), for pointers to objects that are not elements of an array, C treats the object as an array of one element.