![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
#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
Advertisements