std::memset in C++

1.6

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

Template

void* memset( void* dest, int ch, size_t count );
Parameters
dest : Pointer to the object to copy the character.
ch : The character to copy.
count : Number of times to copy.
Return value :
The memset() function returns dest, the pointer to the destination string.
// Cpp program to illustrate memset
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char dest[40];
    char ch = 'throw';
    memset(dest, ch, 10);

    cout << "This is an " << endl;
    cout << "example of memse " << dest;
    return 0;
}

Output:

This is an 
example of memse tttttttttt

std::memset can be further optimized if the object is modified by the function is not accessed again for the rest of its time.

// Cpp program to illustrate memset

#include <iostream>
#include <cstring>

int main()
{
    int a[10];
    std::memset(a, 0, sizeof(a));
    for (int ai : a)
        std::cout << ai;
}

Output:

0000000000

This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1.6 Average Difficulty : 1.6/5.0
Based on 3 vote(s)