C library - memchr() function



The C library memchr() function of type void accepts three agruments that searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str.

Syntax

Following is the syntax of C library memchr() function −

void *memchr(const void *str, int c, size_t n)

Parameters

This function accepts the following parameters−

  • str − This is the pointer to the memory block where the search is performed.

  • c − This is the value to be passed as an int, but the function performs a byte per byte search using the unsigned char conversion of this value.

  • n − This is the number of bytes to be analyzed.

Return Value

This function returns a pointer to the matching byte or NULL if the character does not occur in the given memory area.

Example 1

Following is the C library program to see the demonstration of memchr() function.

#include <stdio.h>
#include <string.h>
int main () 
{
   const char str[] = "Tutorialspoint";
   const char ch = '.';
   char *ret;
   ret = memchr(str, ch, strlen(str));
   printf("String after |%c| is - |%s|\n", ch, ret);
   return(0);
}

Output

The above code produces the following output−

String after |.| is - |.tutorialspoint.com|

Example 2

The program compares two strings using memchr() and determines whether they are equal or not.

#include <stdio.h>
#include <string.h>

int main() {
   const char str1[] = "abcdef";
   const char ch = 'd';

   char* result = (char*)memchr(str1, ch, strlen(str1));

   if (result != NULL) {
       printf("'%c' found at position %ld\n", ch, result - str1);
   } else {
       printf("'%c' not found in the string\n", ch);
   }

   return 0;
}

Output

On execution of above code, we get the following output−

'd' found at position 3

Example 3

Below the program searches for a specific character in a given string using memchr().

#include <stdio.h>
#include <string.h>

int main() {
   const char str[] = "Welcome to India";
   const char ch = 't';

   char* result = (char*)memchr(str, ch, strlen(str));

   if (result != NULL) {
       printf("'%c' found at position %ld\n", ch, result - str);
   } else {
       printf("'%c' not found in the string\n", ch);
   }
   
   return 0;
}

Output

After executing the above code, we get the following output−

't' found at position 8
Advertisements