Home » C solved programs » C string programs

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

It fills the n blocks of str with ch.

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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.