memchr() — Search buffer

Standards

Standards / Extensions C or C++ Dependencies

ISO C
XPG4
XPG4.2
C99
Single UNIX Specification, Version 3

both  

Format

#include <string.h>

void *memchr(const void *buf, int c, size_t count);

General description

The memchr() built-in function searches the first count bytes pointed to by buf for the first occurrence of c converted to an unsigned character. The search continues until it finds c or examines count bytes.

Returned value

If successful, memchr() returns a pointer to the location of c in buf.

If c is not within the first count bytes of buf, memchr() returns NULL.

Example

CELEBM11
⁄* CELEBM11                                      

   This example finds the first occurrence of "x" in                            
   the string that you provide.                                                 
   If it is found, the string that starts with that character is                
   printed.                                                                     
   If you compile this code as MYPROG, then it could be invoked                 
   like this, with exactly one parameter:                                       
        MYPROG skixing                                                          
                                                                                
 *⁄                                                                             
#include <stdio.h>                                                              
#include <string.h>                                                             
                                                                                
int main(int argc, char ** argv)                                                
{                                                                               
  char * result;                                                                
                                                                                
  if ( argc != 2 )                                                              
    printf( "Usage: %s string\n", argv[0] );                                    
  else                                                                          
  {                                                                             
    if ((result = (char *)memchr( argv[1], 'x', strlen(argv[1])) ) != NULL)     
      printf( "The string starting with x is %s\n", result );                   
    else                                                                        
      printf( "The letter x cannot be found in the string\n" );                 
  }                                                                             
}                                                                               
Output
The string starting with x is xing

Related information