内存初始化函数memset()用法详解
2013-04-25 15:59
330 查看
作用:在一段内存中填充某个给定的值,注意填充时是按照字节顺序填充的,而不是按照元素填充。 此方法是对较大的结构体和数组进行清零操作的一种有效方法。 函数形式:memset(void *buffer,int c,size_t n) buffer是需要设置的内存的开始地址;c是期望填充值;n是需要填充的字节数。 例1:一个int a[10]型变量,则memset(a,100,sizeof(int))此操作后,元素a[0]的每个字节的值都是100,即0x64,二进制表 示:01100100,所以元素a[0]为0x64646464,二进制表示:01100100 01100100 01100100 01100100 void main() { int i,a[20]; memset(a,10,5*sizeof(int)); for(i=0;i<20;i++) cout<<a<<endl; } 此函数输出的10个元素并非10,而是每个字节都是00001010组成的int型数。 例2: #include #include void main( void ) { char buffer[] = "This is a test of the memset function"; printf( "Before: %s\n", buffer ); memset( buffer, '*', 4 ); printf( "After: %s\n", buffer ); } Output Before: This is a test of the memset function After: **** is a test of the memset function Memset用来对一段内存空间全部设置为某个字符,一般用在对定义的字符串进行初始化为' '或'\0'; 例:char a[100]; memset(a, '\0', sizeof(a)); 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就非常方便: memset(&stTest,0,sizeof(struct sample_struct)); 如果是数组: struct sample_struct TEST[10]; 则 memset(TEST,0,sizeof(struct sample_struct)*10); memcpy 用来做内存拷贝,你可以拿它拷贝任何数据类型的对象,可以指定拷贝的数据长度。 例:char a[100],b[50]; memcpy(b, a, sizeof(b)); 注意如果用memcpy(b,a,sizeof(a)),很可能会造成b的内存地址溢出。 Strcpy就只能拷贝字符串了,它遇到'\0'就结束拷贝。 例:char a[100],b[50];strcpy(a,b);如用strcpy(b,a),要注意a中的字符串长度(第一个‘\0’之前)是否超过50位,如超过,则会造成b的内存地址溢出。 str也可以用用个参数的strncpy(a,b,n) 原文:http://www.360doc.com/content/11/0120/19/1317564_87917268.shtml |
相关文章推荐
- 内存初始化函数memset()用法详解
- 内存初始化函数memset()
- memset用法详解 1。void *memset(void *s,int c,size_t n) 总的作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c。 2。例子 #include
- C++中memset()函数的用法详解
- memset 函数初始化用法
- memset 函数初始化用法
- c++中内存拷贝函数详解
- Sql server中时间函数用法详解
- Linux进程间通信源码剖析,共享内存(shmget函数详解)
- memset用法详解
- Python help()函数用法详解
- 详解Python中where()函数的用法
- memset函数用法
- VC++, CString的各个函数用法详解与小示例
- sscanf() 函数用法详解
- .net中函数的用法详解
- memset用法详解(转)
- Linux进程间通信源码剖析,共享内存(shmget函数详解)
- unset命令_Linux unset 命令用法详解:删除指定的shell变量或函数
- memset函数初始化数组