void *memset(void *s, int ch, size_t n);(int ch能够是char或int)ios
将s所指向的某一块内存中的每一个字节的内容所有设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数一般为新申请的内存作初始化工做, 其返回值为指向S的指针。windows
memset按字节赋值。数组
void *memset(void *s, int ch, size_t n);函数
char
buffer[20];
memset
(buffer,0,
sizeof
(
char
)*20);
strcpy
(buffer,
"123"
);
int some_func(struct something *a) { … … memset(a,0,sizeof(a)); … }
#include "iostream.h" #include "string.h" #include <afx.h> int main(){ char buf[5]; CString str; CString str1; CString str2; memset(buf,0,sizeof(buf)); for(int i = 0; i<5; i++){ str.Format("%d",buf[i]); str1 +=str ; } str2.Format("%d",str1); cout<<str2<<endl; system("pause"); return 0; }
这样写,有没有memset,输出都是同样测试
include <iostream> #include <cstring> using namespace std; int main(){ char a[5]; memset(a,'1',5); for(int i = 0;i < 5;i++) cout<<a[i]<<" "; system("pause"); return 0; }
而,以下程序想把数组中的元素值设置成1,倒是不可行的spa
#include <iostream> #include <cstring> #include <windows.h> using namespace std; int main() { int a[5]; memset(a,1,20);//若是这里改为memset(a,1,5*sizeof(int))也不能够,由于memset按字节赋值。 for(int i = 0;i < 5;i++) cout<<a[i]<<" "; system("pause"); return 0; }
memset能够方便的清空一个结构类型的变量或数组。 如: struct sample_struct { char csName[16]; int iSeq; int iType; }; 对于变量 struct sample_strcut stTest; 通常状况下,清空stTest的方法: stTest.csName[0]={'\0'}; stTest.iSeq=0; stTest.iType=0; 用memset就很是方便: 1 memset(&stTest,0,sizeof(struct sample_struct)); 若是是数组: struct sample_struct TEST[10]; 则 memset(TEST,0,sizeof(struct sample_struct)*10); 另外: 若是结构体中有数组的话仍是须要对数组单独进行初始化处理的。
来自百度百科。http://baike.baidu.com/view/982208.htmcode