Introduction
memset() function is used to fill a block of memory with a particular value either 0 or -1. It sets the destination value with the given value. Before copying the character, it first converts the signed character into the unsigned character. This function generally increases the readability of the program.
It includes “cstring” header file.
Syntax:
memset(variable name, values, sizeof(variable name));
Now, if we write the below statement.
int a[10]={0};
cout<<a[5];
Our output would be 0 as a[10]={0} initialises all 10 places by 0.
But instead of above code segment, if we write,
int a[10]={5};
cout<<a[5];
The result would again be 0 as this form of initialisation is valid only in case of 0.
Next code segment,
int n;
cin>>n;
int a[n]=0;
cout<<a[5];
Our output would result in compilation error because initialisation of some variable n is not allowed.
To solve these problems, we brought memset.
int n;
cin>>n;
int a[n];
memset(a, 10, sizeof(a));
cout<<a[2];
This segments output some garbage value. This is because it is clearly specified that the value must be assigned only with 0 or -1. In case of string, everything can get replaced.
int n;
cin>>n;
int a[10];
memset(a, -1, sizeof(a));
cout<<a[2];
The output would be -1.
In string data type,
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char str[] = "codingninja";
memset(str, 't', sizeof(str));
cout << str;
return 0;
}
Output:
ttttttttttt
Also see, Fibonacci Series in C++, Abstract Data Types in C++
Memset in 2D Array
int arr[10][20] = {0};
memset(arr, 0, sizeof arr);
All values of the matrix get replaced by 0.
In case of dynamic array,
//initialisng the dynamic array
int *arr = malloc((10*20) * (sizeof *arr));
//copying value.
memset(arr, 0, (10*20*) * (sizeof *arr));
Till now, I assume you must have got a basic idea about memset.
You can also do a free certification of Basics of C++