Understanding Memset() in C++
This blog explains memset() in C++. We have explained this topic with the help of examples. Let’s understand!
In C++, memset() is a library function that populates a memory block with a specific value. It requires three arguments to operate, including a pointer to the beginning address of the memory block, the value to be assigned, and the number of bytes to be filled.
In this tutorial, we will discuss memset() in C++, along with examples to understand the working of the function. We will be covering the following sections:
So, without further ado, let’s get started!
Must Explore – Programming Courses
Introduction to Memset() Function in C++
Memset() is a C++ library function used to fill a memory block with a particular value. This function takes three arguments: a pointer to the starting address of the memory block to be filled, the value to be set, and the number of bytes to be filled.
Here is the syntax for the memset() function:
void* memset( void* obj, int val, size_t num);
Best-suited C++ courses for you
Learn C++ with these high-rated online courses
Parameters of memset()
The memset() function in C++ takes a three parameters:
- obj: A pointer to the initial memory where the values must be added. This can be a string name, a pointer to a string, an array name, a pointer to an array, a vector iterator, etc.
- val: The value to be copied or added.
- num: The number of bytes to be filled.
Return Value of memset()
The return value of memset() in C++ is the pointer to the given object, referred to as obj.
C++ Examples of memset() Function
Example 1: Initializing an integer array with zeroes
#include <iostream> #include <cstring>
using namespace std;
int main() { int arr[5];
// Initialize the integer array with zeros memset(arr, 0, sizeof(arr));
// Print the array for (int i = 0; i < 5; i++) { cout << arr[i] << " "; }
return 0; }
Output:
0 0 0 0 0
This program first declares an integer array arr of size 5. Then, the memset() function is used to initialize all the array elements to 0. The sizeof() operator is used to determine the size of the arr array and pass it as the third argument to memset().
Finally, the program uses a for loop to print the initialized array. The loop iterates over all the elements of the arr array and prints them using the printf() function.
Example 2: Initializing a string with a specific character
#include <iostream> #include <cstring>
using namespace std;
int main() { char str[10] = "Hello";
// Set the first 3 characters of the string to 'A' memset(str, 'A', 3);
// Print the modified string cout << str << endl;
return 0; }
Output:
AAAlo
This C++ program demonstrates using the memset() function to modify the first few characters of a string.
First, the program declares a character array str of size 10 and initializes it with “Hello”.
Next, the memset() function is called with three arguments. The pointer to the starting address of the str array, the character ‘A’ that we want to set the first three characters to. Also, the number of bytes (or characters) we want to fill, which is 3 in this case.
As a result of the memset() function call, the first three characters of str are set to ‘A’, which means that “Hel” is replaced with “AAA”.
Finally, the modified string is printed using the cout statement, and the output is “AAAllo” since the first three characters are now ‘A’.
Example 3: Initializing a struct to 0
#include <iostream> #include <cstring> using namespace std;
struct Person { int age; char name[20]; float height; };
int main() { Person p;
// Initialize the struct with zeros memset(&p, 0, sizeof(p));
// Print the values of the struct cout << "Age: " << p.age << endl; cout << "Name: " << p.name << endl; cout << "Height: " << p.height << endl;
return 0; }
Output:
Age: 0 Name: Height: 0
This C++ program demonstrates using the memset() function to initialize the contents of a struct to zeros. First, the program defines a struct Person with three members: age, name, and height.
Next, the main() function declares a variable p of type Person. Then, the memset() function is called with three arguments: the pointer to the starting address of the p variable. The value 0 that we want to set all members to, and the size of the Person struct. As a result of the memset() function call, all members of the p variable are set to 0.
Finally, the values of the age, name, and height members of the p variable are printed using the cout statements.
Example 4: Setting the last two elements of the array to zero
Output:
#include <iostream> #include <cstring>
using namespace std;
int main() { int arr[5] = {1, 2, 3, 4, 5};
// Set the last two elements of the array to 0 memset(arr + 3, 0, 2 * sizeof(int));
// Print the modified array for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }
1 2 3 0 0
In this example, we declare an integer array arr of size 5 and initialize it with some values. We then use memset() to set the last two elements of the array to 0. We pass the address of the element at index 3 of the array to memset() as the starting address. Also, pass 2 times the size of an integer as the number of bytes to be filled. Finally, we print the modified array to confirm that the last two elements are now 0.
Endnotes
In conclusion, the memset() function is useful in C++ for initializing a block of memory with a specific value. It can quickly initialize arrays, strings, and structures with zeros or other values.
It’s important to note that the memset() function can only be used to set all the bytes in a block of memory to a specific value. If you want to set individual elements of an array or structure to different values, you’ll need to use a loop or another function.
I hope this article was useful to you. Explore our C++ articles to learn more about the language and consolidate your knowledge of the fundamentals.
Contributed By: Prerna Singh
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio