AppDividend
Latest Code Tutorials

C++ memset() Function Example | memset() in C++

0

C++ memset() is an inbuilt function that is used to copy the character to a memory block for n number of times to an object. In simpler words, it is used to fill the memory block with a particular value. It converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[].

C++ memset()

The memset() function in C++ copies a single character for a specified number of time to an object.

Syntax

void* memset(void* str_var, int char_var, size_t num)

It basically converts the char_var to unsigned char datatype and copies the first num characters of the object which is pointed by str_var.

memset() can also be used to assign integer value 0 and -1 to some array. It is strictly restricted to 0 and 1 setting other values won’t work.

Parameters

It takes 3 parameters. First is str_var which is a pointer to the string object.

Second is char_var which is the character we want to copy and third is num which indicates the number of bytes we want to copy.

Return Value

It returns the str_var which is the pointer to the final output string.

Example programs on memset() function in C++

Example 1: Write a program to show the working of the memset() function.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char str_var[] = "HelloWorldIamTheBoss";
  memset(str_var, 'q', sizeof(str_var));
  cout << str_var;

  return (0);
}

Output

qqqqqqqqqqqqqqqqqqqq

Example 2: Write a program to set -1 to all the array elements using memset() function.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  int arr[10];
  memset(arr, -1, sizeof(arr));
  for (int i = 0; i < 10; i++)
  {
    cout << arr[i];
  }

  return (0);
}

Output

 -1-1-1-1-1-1-1-1-1-1

We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set other values. The reason is simple: memset() works byte by byte.

See also

C++ strerror()

C++ strlen()

C++ strstr()

C++ strtok()

C++ strspn()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.