A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_memset.htm below:

C library - memset() function

C library - memset() function

The C library memset() function of type void accepts three variable as parameters that copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.

This function is used to fill a contiguous block of memory with a specific value. It also converts the value of a character to unsigned character and copies it into each of first n character of the object pointed by the given string. If the n is larger than string size, it will be undefined.

Syntax

Following is the syntax of the C library memset() function −

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

This function accepts the following parameters

Return Value

This function returns a pointer to the memory area str.

Example 1

In this example, we set the initial string using C library memset() function, and to modify the string content it has to use memset() function.

#include <stdio.h>
#include <string.h>

int main () 
{
   char str[50];

   strcpy(str, "Welcome to Tutorialspoint");
   puts(str);

   memset(str, '#', 7);
   puts(str);
   
   return(0);
}
Output

The above code produces the following result−

Welcome to Tutorialspoint
####### to Tutorialspoint
Example 2

Below the program initializes an integer array with zeroes using memset().

#include <stdio.h>
#include <string.h>

int main() {
   int arr[10];
   memset(arr, 0, sizeof(arr));

   printf("Array after memset(): ");
   for (int i = 0; i < 10; i++) {
       printf("%d ", arr[i]);
   }
   printf("\n");

   return 0;
}
Output

On execution of above code, we get the following result−

Array after memset(): 0 0 0 0 0 0 0 0 0 0 
Example 3

Here, we create a C program for intializing character array with a specific character('Z') using memset().

#include <stdio.h>
#include <string.h>

int main() {
   char str[20];
   memset(str, 'Z', 10);
   printf("String after memset(): %s\n", str);
   return 0;
}

After executing the code, we get the following result−

String after memset(): ZZZZZZZZZZ

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4