Q:

memset() function in C with Example

belongs to collection: C String Programs

0

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.

All Answers

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

Let’s consider the given example – and learn how ‘memset()’ can be used?

Example:

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

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

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

	//filling all blocks with 0
	memset(arr,0,LEN);
	printf("Array elements are (after memset()): \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
	memset(arr,-1,3);
	memset(arr+3,-2,3);
	memset(arr+6,-3,3);
	printf("Array elements are (after memset()): \n");
	for(loop=0; loop<LEN; loop++)
		printf("%d ",arr[loop]);
	printf("\n");

	return 0;
}

Output

Array elements are (before memset()):
-96 11 67 103 -4 127 0 0 0 0
Array elements are (after memset()):
0 0 0 0 0 0 0 0 0 0
Array elements are (after memset()):
-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 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

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write your own memset() function in C... >>
<< Write your own memcpy() function in C...