C++ memset()

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
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges