memset() is used to fill a block of memory with a particular value.
The syntax of memset() function is as follows :
// ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);
Note that ptr is a void pointer, so that we can pass any type of pointer to this function.
Let us see a simple example in C to demonstrate how memset() function is used:
Before memset(): GeeksForGeeks is for programming geeks. After memset(): GeeksForGeeks........programming geeks.
Explanation: (str + 13) points to first space (0 based index) of the string “GeeksForGeeks is for programming geeks.”, and memset() sets the character ‘.’ starting from first ‘ ‘ of the string up to 8 character positions of the given string and hence we get the output as shown above.
0 0 0 0 0 0 0 0 0 0
Predict the output of below program.
Note that the above code doesn’t set array values to 10 as memset works character by character and an integer contains more than one bytes (or characters).
However, if we replace 10 with -1, we get -1 values. Because representation of -1 contains all 1s in case of both char and int.
Reference: memset man page (linux)
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- memset in C++
- isalpha() and isdigit() functions in C with cstring examples.
- Pointers in C/C++ with Examples
- strtok() and strtok_r() functions in C with examples
- std::mismatch() with examples in C++
- wcscpy() function in C++ with Examples
- wcscmp() function in C++ with Examples
- set_symmetric_difference in C++ with Examples
- ratio_equal() in C++ with examples
- std::equal_to in C++ with Examples
- quick_exit() function in C++ with Examples
- feclearexcept in C++ with Examples
- Understanding Lvalues, PRvalues and Xvalues in C/C++ with Examples
- multiset lower_bound() in C++ STL with Examples
- multiset upper_bound() in C++ STL with Examples
- multiset max_size() in C++ STL with Examples
- forward_list max_size() in C++ STL with Examples
- std::allocator() in C++ with Examples
- array data() in C++ STL with Examples
- multiset size() in C++ STL with Examples
Improved By : abhnv