将值ch转换为无符号char,并将其复制到str []指向的对象的前n个字符中的每个字符中。如果对象不是普通可复制的(例如,标量,数组或C兼容结构),则行为是不确定的。如果n大于str指向的对象的大小,则该行为是不确定的。
模板
void* memset( void* str, int ch, size_t n);
Parameters
str[] : Pointer to the object to copy the character.
ch : The character to copy.
n : Number of bytes to copy.
Return value :
The memset() function returns str, the pointer to the destination string.
CPP
// CPP program to illustrate memset
#include
#include
using namespace std;
int main()
{
char str[] = "geeksforgeeks";
memset(str, 't', sizeof(str));
cout << str;
return 0;
}
CPP
#include
using namespace std;
int main()
{
int a[5];
// all elements of A are zero
memset(a, 0, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// all elements of A are -1
memset(a, -1, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// Would not work
memset(a, 5, sizeof(a)); // WRONG
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
}
输出:
tttttttttttttt
对于整数数据类型,我们可以使用memset()将所有值设置为0或-1。如果将其设置为其他值,它将不起作用。原因很简单,memset逐字节工作。
CPP
#include
using namespace std;
int main()
{
int a[5];
// all elements of A are zero
memset(a, 0, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// all elements of A are -1
memset(a, -1, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// Would not work
memset(a, 5, sizeof(a)); // WRONG
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
}
输出:
0 0 0 0 0
-1 -1 -1 -1 -1
84215045 84215045 84215045 84215045 84215045
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。