Memset in C++
Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is useful for filling a number of bytes with a given value starting from a specific memory location. It is defined in <cstring> header file.
void* memset( void* str, int ch, size_t n);
Memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behavior is undefined.
- str: Pointer to the object to copy the character.
- ch: The character to copy. It can be a character, a normal value as well a boolean value.
- n: Number of bytes to copy.
Return value: The memset() function returns str, the pointer to the destination string.
Time Complexity: O(N) [For traverse from begin to end of the object]
Auxiliary Space Complexity: O(1)
Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.
0 0 0 0 0 -1 -1 -1 -1 -1 84215045 84215045 84215045 84215045 84215045
1 1 1 1 1 true true true true true
NOTE: For boolean the object must be of bool type for C++. Eg. bool arr[n];
Advantages of memset( ) function
1. Increase readability
The main purpose of memset() function is to transform each character of the whole string into a specific int value before passing it as an input. It is a one-line piece of code, making it highly compact and improving readability overall.
2. Reduce lines of code
The same task has been accomplished more quickly than the laborious technique by utilizing this memset() function, which just accepts input, rather than the unneeded usage of loops to assign and convert the value of each character in the string to an int value.
3. It is Faster
The same task has been accomplished quickly as opposed to the time-consuming way by using this memset() function’s input alone, which eliminates the need for needless loops to assign and convert the value of each character in the string to an int value.
4. Useful in getting rid of Misalignment Problem
The C++ memset() function aids the programmer in solving the misalignment issue. There are instances where you discover that the processor is having trouble with data alignment, which results in a programming mistake. The memcpy() and memcmp() methods in C++ are the best options in this situation.
This article is contributed by Pranav. . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.