Function memset( )

what is memset() used for? Any more examples on this.

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

#include <bits/stdc++.h> 
using namespace std; 
   
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; 
   }

Output:

0 0 0 0 0

Memset is also used for character arrays

    #include <cstring> 
    #include <iostream>  
    using namespace std; 
  
int main() 
{ 
    char str[] = "geeksforgeeks"; 
    memset(str, 't', sizeof(str)); 
    cout << str; 
    return 0; 
}
1 Like

@aditya001tomar
Please mark your doubt as resolved if you’ve got it!

@mahimahans111 Thanks !!

1 Like