In this tutorial, you will learn in-depth about C string library function memset()
with explanation and explicit example.
memset()
is built in standard string function that is defined in string header library string.h
. Therefore, to use this function we should include string.h
.
#include<string.h>
void *memset( const void *str, int ch, size_t n );
where,
str = pointer to the object or block of memory that needs to be set
ch = value that is copied, converted to unsigned char
n = number of bytes to be set
This function copies ch
(represented as unsigned char) into the first n
characters of the object or memory block pointed by str
.
memset()
returns a pointer to the block of memory.
[adsense1]
/*Use of string library function memset*/
#include<stdio.h>
#include<string.h>
int main()
{
//initializing character array
char str[ 30 ] = "Learn C from trytoprogram.com";
//displaying str
printf("str = %s\n\n", str);
printf("str after memset( str, '*', 5 ) : %s\n", memset(str, '*', 5));
return 0;
}
Output
Explanation
In the above program, we have copied '*'
into first 5 characters of array str
.