C <string.h> - memchr() Function
The C <string.h> memchr() function is used to find the first occurrence of ch (after conversion to unsigned char) in first num characters of the block of memory (each interpreted as unsigned char) pointed to by ptr.
The function returns pointer to the first occurrence of ch in ptr, or null pointer if ch is not found in ptr.
Syntax
const void * memchr ( const void * ptr, int ch, size_t num ); void * memchr ( void * ptr, int ch, size_t num );
Parameters
ptr |
Specify pointer to the block of memory where the search is performed. |
ch |
Specify the character to search for. |
num |
Specify the maximum number of characters to be examined. size_t is an unsigned integer type. |
Return Value
Returns pointer to the first occurrence of ch in ptr, or null pointer if ch is not found in ptr.
Example:
The example below shows the usage of memchr() function.
#include <stdio.h> #include <string.h> int main (){ char MyStr[100] = "To be, or not to be, that is the question."; char * search; //searching for first occurrence of 'e' //in first 25 characters of MyStr search = (char*) memchr(MyStr, 'e', 25); //displaying the result if(search != NULL) printf("Found at: %ld\n", (search-MyStr+1)); else printf("Not Found.\n"); return 0; }
The output of the above code will be:
Found at: 5
❮ C <string.h> Library