C programming memchr string.h

In C programming the <string.h> memchr function search for the first occurrance of a character in a string.The declaration of the function is given below.

void *memchr(const void *s, int c, size_t n);

s -The pointer to string from which the character is to be searched for.

c -This value is converted to ‘unsigned char’ which is the character to be searched in ‘s’ string.

n -The initial size of the ‘s’ pointed string from which the character is to be searched.

Return type
void* – Returns a pointer to the located character,or a null pointer if the character does not occur in the object.

The ‘size_t’ type defined in string.h is usually an unsigned int.

Code example

char s[] = “A sample text” ;
void *retCh ;

int c1 = ‘a’, c2 = ‘T’;

printf(“%d\n” , strlen(s));

retCh = memchr(s , c1 , strlen(s) );

printf(“retCh=%c” , *((char*)retCh) );

retCh = memchr(s , c2 , strlen(s) ); //Returns NULL

/*printf(“\nretCh=%c” , *((char*)retCh) );   //throws exception in VS cause we are trying to access a NULL pointer



Related links

->C strchr string.h