Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - memset()

C library function - memset()

C Standard Library - <string.h> C Standard Library -

Description

C library function **void memset(void str, int c, size_t n) Used to set a region of memory to a specified value.

The memset() function copies the specified value c to the first n bytes of the memory area pointed to by str; this can be used to zero a memory block or set it to a specific value.

In some cases, you need to quickly initialize a large block of memory to zero or a specific value, and memset() provides an efficient implementation.

When clearing a memory region or assigning a value to it, memset() is a commonly used utility function.

Declaration

void *memset(void *ptr, int value, size_t num);

Here is the declaration of the memset() function.



void *memset(void *str, int c, size_t n)

Parameters

Return Value

The function returns a pointer to the memory area str.

Notes

Example

The following example demonstrates the use of the memset() function.

Example

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

char

str

[

50

]

;

strcpy

(

str

,

"

This is string.h library function

"

)

;

puts

(

str

)

;

memset

(

str

,'$',

7

)

;

puts

(

str

)

;

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:



This is string.h library function

$$$$$$$ string.h library function

Example

#include

#include // Include the string.h header to use memset

int

main

(

)

{

   

char

buffer

[

10

]

;

   

// Set the first 5 bytes of the buffer array to the character 'A', and add a string terminator

   

memset

(

buffer

,

'A'

,

5

)

;

    buffer

[

5

]

=

'\0'

;

// Ensure the string terminator is added

   

printf

(

"Buffer after memset: %s\n"

,

buffer

)

;

   

// Zero the buffer array, using '\0' instead of 0

   

memset

(

buffer

,

'\0'

,

sizeof

(

buffer

)

)

;

// Use '\0' for consistency and readability

   

printf

(

"Buffer after memset: %s\n"

,

buffer

)

;

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



Buffer after memset: AAAAA

Buffer after memset: 

C Standard Library - <string.h> C Standard Library -