memset in C++


In this section we will see what is the purpose of memset() function in C++. This function 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 str[]. If the n is larger than string size, it will be undefined.

The syntax of the memset() function

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

In this example will use one string, then convert each character to some other character up to length n.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int main() {
   char str[] = "Hello World";
   memset(str, 'o', 6); //take n = 6
   cout << str;
}

Output

ooooooWorld

The memset() can be uses to set all values to 0 or -1. But we cannot use some other values, because memset() works byte by byte.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int main() {
   int array[10];
   memset(array, 0, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
      memset(array, -1, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
      memset(array, 3, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
}

Output

0 0 0 0 0 0 0 0 0 0
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
50529027 50529027 50529027 50529027 50529027 50529027 50529027
50529027 50529027 50529027

Updated on: 30-Jul-2019

819 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements