A C string is a sequence of char values that ends with a null character, written '\0'. C has no separate string type, so the array is the string. The null character is how functions such as strlen() know where the text stops.
How a C string is stored
char greeting[] = "Hello";
The array holds six elements:
index: 0 1 2 3 4 5
value: H e l l o \0
The text has five visible characters. The sixth element, the null character, takes one slot in the array.
Why the null character matters
Functions in <string.h> read a C string until they reach '\0'. An array without that terminator has no end marker, so these functions keep reading past the end of the array into memory that is not part of it, which is undefined behavior.
The null character '\0' is different from a null pointer. What is a null pointer in C covers the pointer case.
Creating C strings
There are two common ways to make one. An array with an initial value sizes itself to fit the text and the terminator:
char name[] = "Ada"; /* four elements: 'A', 'd', 'a', '\0' */
If arrays are new to you, what is an array in C with an example introduces them. A pointer to a string literal is the other common form:
const char *message = "Hi"; /* pointer to a string literal */
Changing the text of a string literal is undefined behavior, so use a const pointer for text you only read. When you plan to fill an array later, choose a size with room for the terminator.
Measuring a C string
sizeof and strlen() give different answers for a char array, which is a common source of confusion:
#include <stdio.h>
#include <string.h>
int main(void) {
char greeting[] = "Hello";
printf("sizeof: %zu\n", sizeof greeting); /* 6 */
printf("strlen: %zu\n", strlen(greeting)); /* 5 */
return 0;
}
sizeof gives the size of the array, including the terminator. strlen() gives the number of characters before the terminator.
Arrays and pointers
Functions usually receive a C string as a pointer to its first character, even when the variable itself is an array. Whether a C string is an array or a pointer is explained in Is char[] and char * the same in C?
C strings and std::string
std::string stores its length and manages its own memory, so you do not track the terminator yourself. The member functions are listed in C++ String Methods. To convert an existing char array into a std::string, see how to convert C string to string.
Common mistakes
- Forgetting the slot for the null character. A five-letter word needs six elements.
- Comparing two C strings with
==, which compares their addresses. Usestrcmp()instead. - Writing to a string literal, which is undefined behavior.
- Returning a pointer to a local array. The array no longer exists after the function returns:
char *make_name(void) {
char buffer[10] = "Ada";
return buffer; /* buffer no longer exists after the return */
}