×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

Write your own memset() function in C

Here, we are going to learn how to write your own memset() function to fill blocks of memory with a particular value in C?
Submitted by IncludeHelp, on December 07, 2018

As we have discussed in the previous post that memset() is a library function of “string.h” and it is used to fill the memory blocks with a particular value.

Read more: memset() function in C

Writing your own memset() function in C

Here, we are going to create our own "memset()" function...

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

C program to write your own memset() function

#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.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.