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.

Categorystring.h strings
KindLibrary function
Header<string.h>
C standardC89 / C90

📝 Syntax

size_t strlen(const char *str);

⚙️ Parameters

str RequiredA 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏