Write your own memset() function in C
Function prototype:
void myMemSet(void* str, char ch, size_t n);
It will fill n blocks of the str with ch.
Function definition:
//memset() function implemention
//function name: myMemSet()
void myMemSet(void* str, char ch, size_t n){
int i;
//type cast the str from void* to char*
char *s = (char*) str;
//fill "n" elements/blocks with ch
for(i=0; i<n; i++)
s[i]=ch;
}
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 myMemSet() 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