In this guide, you will learn what is memset() function is in C++ programming and how to use it with an example.
1. memset() Function Overview
The memset() function in C++ is used to set the first n bytes of the block of memory pointed by ptr to the specified value (converted to an unsigned char). It's a part of the C++ <cstring> header. This function is commonly used to initialize a block of memory, often for setting an array or a structure to zero.
Signature:
void* memset(void* ptr, int value, size_t n);
Parameters:
- ptr: Pointer to the block of memory to fill.
- value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
- n: Number of bytes to be set to the value.
2. Source Code Example
#include <iostream>
#include <cstring>
int main() {
char str[50] = "SourceCodeExamples is for programming geeks.";
// Setting 5 characters starting from 2nd index to '*'
memset(str + 2, '*', 5);
std::cout << str;
return 0;
}
Output:
So*****odeExamples is for programming geeks.
3. Explanation
In the provided source code:
1. We include the necessary header files: <iostream> for input/output operations and <cstring> for memset().
2. A character array str is defined and initialized with a string.
3. The memset() function is used to set a portion of the string to the character '*'.
4. The result is then printed to the screen.
Comments
Post a Comment