memset() function in C with Example
memset() function in C
Function memset() is a library function of "string.h" – it is used to fill a block of memory with given/particular value. It is used when you want to fill all or some of the blocks of the memory with a particular value.
Syntax of memset():
memset(void *str, char ch, size_t n);
It fills the n blocks of str with ch.
Let’s consider the given example – and learn how ‘memset()’ can be used?
Example:
Output
Explanation:
In this example, we declared character array arr of LEN bytes (LEN is a macro with the value 10), when we printed the value of arr, the output is garbage because array is uninitialized. Then, we used memset() and filled all elements by 0. Then, printed the elements again the value of all elements were 0. Then, we filled first 3 elements with -1 and next 3 elements with -2 and next 3 elements with -3. Thus the values of all elements at the end: -1 -1 -1 -2-2 -2 -3 -3 -3 0.
need an explanation for this answer? contact us directly to get an explanation for this answer