The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

memchr() In C

Purpose Of memchr()

memchr() is one of the inbuilt string function in c programming which is used to find the first occurance of a character chr in a string str of length n.

How memchr() Works

The following diagram clearly illustrate the working principle of memchr() inbuilt string function in C.

memchr() in c

In the above diagram memchr() takes 3 parameters, first parameter holds a string str, second parameter holds a character chr to be find in a string str, third parameter holds an integer value to set limitation for a search in string str.

Syntax Of memchr()

  • memchr() accepts three parameters
  • First parameter is a string, second parameter character and third paramter must be a integer.
  • To use memchr() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
memchr(str, chr, n);

C Program - memchr()

Let us work through memchr() function, In the following program we will find the first occurance of a character chr in a string str of length n using memchr() inbuilt string function.

c-using-memchr.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "asp.net.";
char chr = '.';
char *res;
res = memchr(str, chr, 4);
printf("%s", res);
return 0;
}
.net.

Note:

The above program defines the function memchr() which is used to find ' . ' in a string "asp.net" within first 4 character.

C Program - Without memchr()

Let us find the first occurance of a chracter chr in a string str of length n without using memchr() inbuilt string function.

c-without-memchr.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "asp.net.";
char chr = '.', i, n = 4, j;
for(i=0; str[i] !='\0'; i++ )
{
if(str[i] == chr) {
for(j=i; str[j]!='\0';j++)
printf("%c", str[j]);
break;
}
}
return 0;
}
.net.

Note:

The above program looks verbose but yields the same result.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report