What is wmemchr in C?
The wmemchr function is used to look for the occurrence of a wide character in a wide string. The function is defined in the wchar.h header.
Parameters
wchar_t* wmemchr (wchar_t* str, wchar_t wc, size_t count);
The function takes three parameters.
In the above snippet of code, wc is a wide character searched in the wide string pointed by str. This search will be done for the first count number of characters in str.
Return value
If wc is found in str, the function returns a pointer to its first occurrence.
The function returns NULL if wc is not found in str or if count is 0.
Difference between wmemchr and wcschr
The wcschr function searches a wide character in a wide string, whereas the wmemchr function searches a wide character in a memory block.
In simple words, the wcschr function stops searching when it reads a null wide character. On the other hand, wmemchar searches until count number of characters, even if a null wide character is encountered.
More information about
wcschrfunction can be found here
Example 1
#include<stdio.h>#include<wchar.h>void main() {// declaring and initializing wide stringwchar_t str1[] = L"HELLO WORLD";// calling the functionwchar_t* ptr = wmemchr(str1, L'W', 11);// using the wprintf function to print the wide stringwprintf(L"ptr: %ls\n\n", ptr);}
In the above snippet of code, we search the wide character ‘W’ from str1. The function returns the pointer to the first occurrence of ‘W’, which is stored in ptr.
Example 2
#include<stdio.h>#include<wchar.h>void main() {// declaring and initializing wide stringwchar_t str1[] = L"HELLO WORLD. \0 I AM A MACHINE";// calling the functionwchar_t* ptr = wmemchr(str1, L'I', 30);wchar_t* ptr2 = wcschr(str1, L'I');// using the wprintf function to print the wide stringwprintf(L"RESULT WITH wmemchr: \n");wprintf(L"ptr: %ls\n\n", ptr);wprintf(L"\nRESULT WITH wcschr: \n");wprintf(L"ptr2: %ls\n\n", ptr2);}
In the snippet of code above, we can see that the wmemchr function continues to search the wide character ‘I’ even after the null wide character. It returns a pointer to the first occurrence of ‘I’ even after the null wide character. On the other hand, the wcschr function returns NULL because it does find ‘I’ before the null wide character.
Free Resources