strchr() Find the first occurrence of a character

strchr() Find the first occurrence of a character

strchr() finds the first c, including the null terminator, returning a pointer or NULL. Check before dereferencing or subtracting str for an index.

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

📝 Syntax

char *strchr(const char *str, int c);

⚙️ Parameters

str RequiredThe null-terminated string to search.
c RequiredThe character to locate, converted to char for comparison.

Returns: Returns a pointer to the located character, or NULL if the character is not found.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

First n: nana
⚠️ Warning The returned pointer refers inside the original string, not to a newly allocated copy. It must not be used after that storage becomes invalid.
💡 Tip The index of the first occurrence is found - str, provided found is not NULL.

📚 Related Tutorials

❓ FAQ

QCan strchr find a string's terminating null character?
AYes. Pass '\0' as the second argument; a successful result points to the string's terminating null character.
QWhat does strchr return when the character is absent?
AIt returns NULL. Check the result before dereferencing it, computing an index, or passing it to a string function.
QHow can I convert the pointer returned by strchr into a character index?
AFirst confirm that the returned pointer is not NULL, then use found - str to obtain an index of type ptrdiff_t, since both pointers refer into the same character array. Subtracting after a failed search involves null-pointer arithmetic; the result also cannot be used to compute a position after the original array's lifetime has ended.
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%

🙏 帮我们做得更好

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

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