C string library function memset()


In this tutorial, you will learn in-depth about C string library function memset() with explanation and explicit example.

c string library function memset()

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>

Function prototype of C string library function memset()

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.

C program to demonstrate the function of string library function memset()

/*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

output c memset

Explanation

In the above program, we have copied '*' into first 5 characters of array str.