w3resource

C memchr() function

C memchr() function - find byte in memory

Syntax:

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

The memchr() function is used to search the first n bytes of buf for the first occurrence of c converted to an unsigned character.

Parameters:

Name Description Required /Optional
buf Pointer to buffer. Required
c Character to look for. Required
n Number of characters to check. Required

Return value from memchr()

The memchr() function returns a pointer to the location of c in buf. It returns NULL if c is not within the first count bytes of buf.

Example: memchr() function

The following example shows the usage of memchr() function.

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

int  ch1= 'A', ch2 = 'a';
char text[] = "C programming language.";
int main()
{
   char *pdest;
   int result;
   printf("Original String: %s", text );
   printf("\n\nCheck the character %c present in the said text!",ch1);
   pdest = (char *)memchr(text, ch1, strlen(text));
   result = (int)(pdest - text + 1);
   if ( pdest != NULL )
      printf( "\n%c found at position %d\n", ch1, result );
   else
      printf("\n%c not found!",ch1 );
   printf("\n\nCheck the character %c present in the said text!",ch2);
   pdest = (char *)memchr(text, ch2, strlen(text));
   result = (int)(pdest - text + 1);
   if ( pdest != NULL )
      printf( "\n%c found at position %d\n", ch2, result );
   else
      printf("\n%c not found!",ch2);
 return 0;
}

Output:

Original String: C programming language.

Check the character A present in the said text!
A not found!

Check the character a present in the said text!
a found at position 8

C Programming Code Editor:

Previous C Programming: C string.h Home
Next C Programming: C memcmp()



Follow us on Facebook and Twitter for latest update.