memchr C Library Function

The function void *memchr(const void *str, int ch, size_t n) searches for first occurrence of character ch in first n bytes of block of memory(string) pointed by pointer str.

Function prototype of memchr

void *memchr(const void *str, int ch, size_t n);
  • str : Pointer to the block of memory where we are searching.
  • ch : Value to be searched. The value is passed as an integer, but memchr function performs a byte per byte search using the unsigned char conversion of this value.
  • n : This is the number of bytes to be searched, starting from location pointed by pointer str.

Return value of memchr

It returns a pointer to the first occurrence of ch in the block of memory pointed by str. If ch is not found, then function returns a NULL pointer.

C program to show the use of memchr function

The following program shows the use of memchr function to search a character in a string.

memchr C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char string[100];
   char ch, *ptr;
   printf("Enter any string\n");
   gets(string);
   printf("Enter any character to search\n");
   scanf("%c", &ch);
    
   ptr = memchr(string, ch, strlen(string));
 
   if(NULL == ptr){
      printf("'%c' not found in string \"%s\"\n", ch, string);
   } else {
      printf("String after %c is \"%s\"\n", ch, ptr);
   }
    
   getch();
   return(0);
}

Output

CStandardLibraryFunction
Enter any character to search
L
String after L is "LibraryFunction"
Enter any string
CStandardLibraryFunction
Enter any character to search
z
'z' not found in string "CStandardLibraryFunction"