memset函数功能

来源:互联网 发布:编程入门先学什么语言 编辑:程序博客网 时间:2024/06/01 08:24

memset

功能:将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值。块的大小由第三个参数指定,这个函数通常为新申请的函数作初始化工作。

用法:void memset(void *s,int i,unsigned n);

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int main(){    char buffer[]="Hello world";    printf("buffer before memset: %s\n",buffer);    memset(buffer,'*',strlen(buffer));    printf("strlen=%d\n",strlen(buffer));    printf("sizeof=%d\n",sizeof(buffer));    printf("buffer after memset: %s\n",buffer);    return 0;}
输出结果:

buffer before memset: Hello world
strlen=12
sizeof=13
buffer after memset: ************
(从网上贴来代码时,自己试了试,发现,如果用sizeof()会发生些错误,因为sizeof()会把字符串结尾的\0也改变,所以对字符串进行操作时,用strlen好点。)

也不一定就是把内容全部设置成ch所指定的ASCII值,而且该处的ch可为int或者其他类型,并不一定要是char类型。

例如:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int main(){    int a[5],i;    for(i=0;i<5;i++) a[i]=i+1;    for(i=0;i<5;i++) printf("%d ",a[i]);puts("");    memset(a,0,20);//memset(a,0,sizeof(int));memset(a,0,sizeof(int)*5);    for(i=0;i<5;i++) printf("%d ",a[i]);puts("");    return 0;}
输出结果:

1 2 3 4 5
0 0 0 0 0


后面的表大小的参数是以字节为单位,所以,对于int或者其他的就不是都乘默认的1(字符型)了。而且不同的机器上int的大小也可能不同,所以最好用sizeof()。


要注意的是,memset是对字节进行操作,所以上述程序如果改为:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int main(){    int a[5],i;    for(i=0;i<5;i++) a[i]=i+1;    for(i=0;i<5;i++) printf("%d ",a[i]);puts("");    memset(a,1,sizeof(a));    for(i=0;i<5;i++) printf("%d ",a[i]);puts("");    return 0;}
输出结果:

1 2 3 4 5
16843009 16843009 16843009 16843009 16843009

为什么呢?

因为memset是以字节为单位就是对a指向的内存的5个字节进行赋值,每个都用ASCII的字符去填充,转为二进制后,1就是00000001,占一个字节。一个int是4个字节,合在一起就是00000001000000010000000100000001,就等于16843009,就完成了对一个int元素的赋值了。


补充:某人的一点心得

memset可以方便地清空一个结构类型的变量或者数组。

如:

struct sample_struct  {    char csName[16];    int iSeq;    int iType;};
对于变量

struct sample_struct stTest;

一般情况下,清空stTest的方法:

stTest.csName[0]='\0';

stTest.iSeq=0;

stTest.iType=0;

使用memset就非常方便:

memset(&stTest,0,sizeof(struct sample_struct));

如果是数组:

struct sample_struct TEST[10];

则:

memset(TEST,0,sizeof(TEST));
转自:http://baike.baidu.com/view/982208.html?wtp=tt