C++ memset()

The memset() function in C++ copies a single character for a specified number of time to an object.

memset() prototype

void* memset( void* dest, int ch, size_t count );

The memset() function takes three arguments: dest, ch and count. The character represented by ch is first converted to unsigned char and then copies it into the first count characters of the object pointed to by dest.

The behaviour of the function is undefined if:

  • The object is not trivially copyable.
  • count is greater than the size of dest.

It is defined in <cstring> header file.

memset() Parameters

  • dest: Pointer to the object to copy the character.
  • ch: The character to copy.
  • count: Number of times to copy.

memset() Return value

The memset() function returns dest, the pointer to the destination string.

Example: How memset() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char dest[50];
    char ch = 'a';
    memset(dest, ch, 20);

    cout << "After calling memset" << endl;
    cout << "dest contains " << dest; 
    return 0;
}

When you run the program, the output will be:

After calling memset
dest contains aaaaaaaaaaaaaaaaaaaa