C library function -memset()
C Standard Library - <string.h>
Description
C Library Functionsvoid *memset(void *str, int c, size_t n)Used to set a block 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, which can be used to clear a memory block or set it to a specific value.
In some cases, when it is necessary to quickly initialize a large block of memory to zero or a specific value, memset() can provide an efficient implementation.
When clearing a memory area or assigning a value to a memory area, memset() is a commonly used utility function.
Declaration
void *memset(void *ptr, int value, size_t num);The following is the declaration of the memset() function.
void *memset(void *str, int c, size_t n)
Parameter
- str-- A pointer to the memory area to be filled.
- c-- The value to be set, usually an unsigned character.
- n-- The number of bytes to be set to that value.
Return Value
This function returns a pointer to the memory area str.
Notes
memset()not on pointersptrNo boundary checks are performed on the pointed-to memory area; therefore, when using it, ensureptrthat the pointed-to memory area is large enough to avoid out-of-bounds access.memset()the second parametervalueusually aintA value of type, but actually only the low 8 bits of the value are used. This means in the range0to255values outside this range may produce undefined behavior.numThe parameter indicates the number of bytes to be set, usually viasizeof()or obtained by other means.
Example
The following example demonstrates the usage of the memset() function.
Example
Let us compile and run the above program, which will produce the following result:
This is string.h library function $$$$$$$ string.h library function
Example
#include <string.h> // Include the string.h header file 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'; // Make sure to add the string terminator
printf("Buffer after memset: %s\n", buffer);
// Clear the buffer array to zero, 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 us compile and run the above program, which will produce the following result:
Buffer after memset: AAAAA Buffer after memset:other extensions