C++ Programs: Memset
The C++ function 'memset' is commonly used to set a block of memory with a particular value. It is particularly useful when working with dynamically allocated memory and arrays.
Syntax
void *memset(void *pointer, int value, size_t num);
where:
- 'pointer' is a pointer to the block of memory to be filled
- 'value' is the value to be set
- 'num' is the number of bytes to be set
Example
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[50];
strcpy(str,"This is a string");
cout << "Before memset: " << str << endl;
memset(str,'$',7);
cout << "After memset: " << str << endl;
return 0;
}
Output
Before memset: This is a string
After memset: $$$$$$$is a string
Explanation
In the above example, we have first initialized a string "str" with "This is a string". Then we have printed the string before calling memset.
We then called the function memset to set the first 7 bytes of "str" with "$". The output after the memset shows that the first 7 characters have been replaced with "$".
Use
The 'memset' function can be used to initialize memory, set flags, or to fill an array. It is particularly useful in cases where you have dynamically allocated memory and you want to initialize it with a particular value.
Important Points
- The 'memset' function fills a block of memory with a particular value.
- It can be used to set memory, initialize variables and fill arrays.
- The function is declared in the
header file. - The first argument of 'memset' is a pointer to the memory to be filled.
- The second argument is the value to be filled.
- The third argument is the number of bytes to be filled.
Summary
In summary, the C++ 'memset' function is a useful tool to set blocks of memory with a particular value. It can be used to initialize dynamically allocated memory, set flags, or fill arrays with a particular value. It is simple, efficient, and an essential tool in C++ programming.