Copying data using the memset() function in C
In C, the memset() function stores a specific character in the first n number of places of a memory block.
Syntax
The general syntax for the memset() function is:
void *memset(void *string, int c, size_t n)
Parameters
Let’s look at the parameters that the memset() function takes as input:
-
string: Pointer to the memory block where data will be set
-
C: The character to be copied
-
N: The number of bytes to be set
Note:
- The pointer has been declared
void *so that it may be used for any data type.- The character c is passed as an integer value but it is converted to an unsigned character.
Return value
The function returns a pointer to the memory block string.
Examples
- Let’s look at a simple example of modifying a string to understand the use of the
memset()function.
#include<stdio.h>#include <string.h>int main() {char string[20] = "Hello World!";printf("String before memset(): %s \n", string);memset(string, '*', 4 * sizeof(string[0])); //setting first 4 characters to '*'printf("String after memset(): %s \n", string);return 0;}
Note: Since a character is of 1 byte, to set 4 characters, we will pass n as 4
- Using
memset()on a block of memory storing Integer values is just as simple. Execute the following code to see how it works:
#include<stdio.h>#include <string.h>int main() {int str[5] = {1,2,3,4,5};/* Printing array before memset */for (int i=0;i<5;i++){printf("%d \t", str[i]);}printf("\n");/* setting first 2 elements to 0 */memset(str, 0, 8);/* Printing array after memset */for (int i=0;i<5;i++){printf("%d \t", str[i]);}return 0;}
Note: Since an Integer is of 4 bytes, to set the first 2 elements of the array, we will pass n as 8, i.e. 4 * 2 = 8
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved