The memchr () function in C

The function void * memchr (const void * str, int c, size_t n) looks for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to by parameter str.

Declaring the function memchr () in C

Below is the declaration for memchr () in C:

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

Parameters

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

c - This is the value to be transmitted in the form of an int, but the function performs a byte search using the unsigned char conversion of this value.

n - This is the number of bytes to be analyzed.

Returns the value

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

For example

The following program C illustrates the usage of memchr () in C:

 #include #include int main () { char * pch ; char str [] = "Hoc C co ban va nang cao tai QTM" ; pch = ( char *) memchr ( str , 'v' , strlen ( str )); if ( pch != NULL ) printf ( "Tim thay 'v' tai vi tri %d.n" , pch - str + 1 ); else printf ( "Khong tim thay ky tu 'v'.n" ); return 0 ; } 

Compiling and running the above C program will result:

The memchr () function in C Picture 1

According to Tutorialspoint

Last lesson: string.h in C

Next lesson: Function memcmp () in C

5 ★ | 1 Vote

May be interested

  • The function memcmp () in CPhoto of The function memcmp () in C
    the function int memcmp (const void * str1, const void * str2, size_t n)) compares the first n bytes of two strings str1 and str2.
  • The function wcstombs () in CPhoto of The function wcstombs () in C
    function size_t wcstombs (char * str, const wchar_t * pwcs, size_t n) convert wide-char string defined by pwcs into a multibyte string starting at str. almost all n bytes are written to str ..
  • The function memcpy () in CPhoto of The function memcpy () in C
    function void * memcpy (void * str1, const void * str2, size_t n) copies n characters from str2 to str1.
  • The strstr () function in CPhoto of The strstr () function in C
    char * function strstr (const char * haystack, const char * needle) looks for the final occurrence of the whole needle string (not including the ending null character) that is present in the haystack string.
  • The getchar () function in CPhoto of The getchar () function in C
    the function int getchar (void) in library c takes a character (an unsigned char) from stdin. this function is equivalent to the getc function with the parameter stdin.
  • Function putc () in CPhoto of Function putc () in C
    the function int putc (int char, file * stream) in library c writes one character (an unsigned char) defined by the parameter char to the given stream and increases the position indicator for that stream.