memset() function in C with Example

string.h memset() function with example: Here, we are going to learn about the memset() function of string.h in C/C++ language, which is used to fill a block of memory with the given value.
Submitted by IncludeHelp, on December 07, 2018

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

Parameters of memset()

It fills the n blocks of str with ch.

C - memset() Function Example

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

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

C String Programs »

Related Programs




Comments and Discussions!

Load comments ↻






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