Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Memset in C++

  • Difficulty Level : Easy
  • Last Updated : 08 Dec, 2021

Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is defined in <cstring> header file.

Syntax:

void* memset( void* str, int ch, size_t n);

Memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[]. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behavior is undefined. 

Parameters:

  • str[] : Pointer to the object to copy the character.
  • ch : The character to copy.
  • n : Number of bytes to copy.

Return value: The memset() function returns str, the pointer to the destination string. 

CPP




// CPP program to demonstrate memset
#include <cstring>
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    char str[] = "geeksforgeeks";
    memset(str, 't', sizeof(str));
    cout << str;
    return 0;
}


Output

tttttttttttttt

Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.  

CPP




// CPP Program to demonstrate that we can use memset() to
// set all values as 0 or -1 for integral data types also
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    int a[5];
 
    // all elements of A are zero
    memset(a, 0, sizeof(a));
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    cout << endl;
 
    // all elements of A are -1
    memset(a, -1, sizeof(a));
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    cout << endl;
 
    // Would not work
    memset(a, 5, sizeof(a)); // WRONG
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
}


Output

0 0 0 0 0 
-1 -1 -1 -1 -1 
84215045 84215045 84215045 84215045 84215045 

See Also:

This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.  


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!