Q:

Write your own memset() function in C

belongs to collection: C String Programs

0

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example:

#include <stdio.h>
#include <string.h>
#define LEN 10

//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;
}

int main(void) {
	char arr[LEN];
	int loop;

	printf("Array elements are (before myMemSet()): \n");
	for(loop=0; loop<LEN; loop++)
		printf("%d ",arr[loop]);
	printf("\n");

	//filling all blocks with 0
	myMemSet(arr,0,LEN);
	printf("Array elements are (after myMemSet()): \n");
	for(loop=0; loop<LEN; loop++)
		printf("%d ",arr[loop]);
	printf("\n");

	//filling first 3 blocks with -1
	//and second 3 blocks with -2
	//and then 3 blocks with -3
	myMemSet(arr,-1,3);
	myMemSet(arr+3,-2,3);
	myMemSet(arr+6,-3,3);
	printf("Array elements are (after myMemSet()): \n");
	for(loop=0; loop<LEN; loop++)
		printf("%d ",arr[loop]);
	printf("\n");

	return 0;
}

Output

Array elements are (before myMemSet()):
64 86 -85 42 -4 127 0 0 0 0
Array elements are (after myMemSet()):
0 0 0 0 0 0 0 0 0 0
Array elements are (after myMemSet()):
-1 -1 -1 -2 -2 -2 -3 -3 -3 0

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

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to compare strings using strcmp() functi... >>
<< memset() function in C with Example...