strlen() Compute the length of a string
strlen() Compute the length of a string
strlen() counts characters before the null terminator as size_t. Unterminated input causes undefined behavior; it cannot reveal array capacity.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
size_t strlen(const char *str);
⚙️ Parameters
| str Required | A pointer to a valid null-terminated string. |
|---|
Returns: Returns the number of characters in the string, excluding the terminating null character.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Length: 5
⚠️ Warning Passing an array without a terminating null character makes strlen() read out of bounds, causing undefined behavior.
💡 Tip C89 has no %zu conversion, so the example casts size_t to unsigned long and prints it with %lu.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QDoes strlen include the terminating null character in the length?
ANo. Consequently, copying a string of length len normally requires at least len + 1 bytes in the destination array.
QCan strlen determine the size of any character array?
ANo. It counts only until a null character and knows nothing about array capacity. Use sizeof in the array's declaration scope to obtain its total size.
QWhy do strlen and sizeof produce different results for strings?
Astrlen counts at runtime up to the first null character, excluding the terminator; sizeof yields the object size of a type or array. For a character array, sizeof normally includes the terminator and unused capacity. For a char * pointer, it yields only the pointer size and cannot reveal the length of the pointed-to string.