C++ Standard Library C++ STL Library

C++ <cstring> - memset() Function



The C++ <cstring> memset() function converts value to unsigned char and copies it into each of the first num characters of the object pointed to by ptr.

The behavior is undefined if num is greater than the size of the object pointed to by ptr.

Syntax

void * memset ( void * ptr, int value, size_t num );                

Parameters

ptr Specify pointer to the object to fill.
value Specify the fill byte .
num Specify the number of characters to fill.
size_t is an unsigned integer type.

Return Value

Returns ptr.

Example:

The example below shows the usage of memset() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char str[50] = "Hello World!";

  //displaying str
  cout<<"str is: "<<str<<"\n";

  //setting first 5 characters of str to $ 
  memset(str, '$', 5);

  //displaying str
  cout<<"str is: "<<str<<"\n";
  
  return 0;
}

The output of the above code will be:

str is: Hello World!
str is: $$$$$ World!

❮ C++ <cstring> Library