std::memset
Defined in header <cstring> (‘<”>’的转义为
<
and>
)
void* memset( void* dest, int ch, std::size_t count);
Converts the value ch to
unsigned char
and copies it intoeach of the first count characters of the object pointed to by dest.Parameters
dest - pointer to the object to fill
ch - fill byte
count - number of bytes to fillReturn value
dest
Example
#include<iostream>
#include<cstring>
int main() {
int a[20];
std::memset(a,0,sizeof a);
for(int ai : a) std::cout<<ai;
}
output : 00000000000000000000
用法
- 常用于内存空间初始化
char a[50];
memset(a,'c',50);
memset(a,'/0',sizeof(a));
// 初始化int数组有所不同
int a[20];
memset(a,0,sizeof(a)); // or memset(a,-1,sizeof(a));
// 对于int数组,不能将其初始化为'0' '-1'以外的其他值
// (除非该值高字节和低字节相同)
// 因为memset是按字节对内存块进行初始化
- 方便地清空一个结构类型的变量或数组
struct my_struct test;
memset(&test,0,sizeof(struct my_struct));
struct my_struct Test[10];
memset(Test,0,sizeof(struct my_struct)*10);
Tips: 当静态数组作为参数传入某个函数时,就会退化为指针,即该数组的首地址,会丢失其长度信息。所以数组作参数传递时要同时传入数组长度 或 直接用引用&
References