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.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
char *strchr(const char *str, int c);
⚙️ Parameters
| str Required | The null-terminated string to search. |
|---|---|
| c Required | The 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 string.h functions
📚 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.