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

memset() In C

Purpose Of memset()

memset() is one of the inbuilt string function in c programming which is used to replace first n characters of a string str with a character chr.

How memset() Works

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

memset() in c

In the above diagram memset() takes three parameter say str, chr and n. First n characters of a string str will be replaced by a character chr.

Syntax Of memset()

  • memset() accepts three parameters.
  • First parameter is a array of string, second parameter is a character which you need to replace with and third parameter is a integer which tells the compiler how many characters to be replaced from the string str.
  • To use memset() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
memset(str, setchar, n);

C Program - memset()

The above program defines the function memset(), which replace n characters of a string str.

c-using-memset.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[30] = "what the hell";
memset(str,'*',4);
puts(str);
return 0;
}
**** the hell

Note:

The above program defines the function memset(), which replace n characters of a string str.

C Program - Without memset()

Let us replace n character of a string str without using any inbuilt string function.

c-without-memset.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[30] = "what the hell";
char chr = '*', i, num = 4;
for(i=0; str[i]!='\0'; i++)
{
str[i] = chr;
if(i == num-1)
break;
}
puts(str);
return 0;
}
**** the hell

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