memset,memcpy与memmove,strcpy

来源:互联网 发布:mac口红a17是什么颜色 编辑:程序博客网 时间:2024/05/19 22:01
void *memset( void *buffer, int ch, size_t count ); 
memset函数将buffer的前count项设置成ch 

void *memcpy(void *dst,void *src,size_t count); 
memcpy函数用来进行内存拷贝,用户可以使用它来拷贝任何数据类型的对象。由src所指内存区域将count个字节复制到dst所指内存区域。但是src和dst所指内存区域不能重叠,该函数返回指向dst的指针。 

void* memmove(void* dst,const void* src,size_t count); 
memmove的作用是将一块内存区域中的数据移向另一块区域,它将返回指向目标区域值的指针。如果src和dst所指内存区域重叠,那么该函数会在重叠区域被重写之前对其中内容进行拷贝。 

char* strcpy(char* dst,char* src) 
strcpy函数的功能是把src所指的由NULL结束的字符串复制到dst所指的字符串中。其中,src和dst所指内存区域不可以重叠,且dst必须有足够的空间来容纳src的字符串,该函数返回指向dest的指针。 

strcpy与memcpy的差别 
strcpy只能用来做字符串的拷贝,而memcpy是用来做内存拷贝的,strcpy会一遇到'\0'就结束copy,而memcpy不会 

memmove与memcpy的差别 
体现在dest的头部和src的尾部有重叠的情况下 

C++代码  收藏代码
  1. #include<iostream>  
  2. #include<string.h>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     char *c = "abc";  
  8.     char *d = new char[sizeof(c)+1];  
  9.     strcpy(d,c);  
  10.     d[sizeof(d)-1]='\0';  
  11.     cout << "strcpy c to d:" << d << endl;  
  12.     char e[10];  
  13.     memset(e,'3',5);  
  14.     cout << "memset:" << e << endl;  
  15.     char f[11];  
  16.     memcpy(f,e,sizeof(e));  
  17.     cout << "memcpy from e to f:" << f << endl;  
  18.     char g[10];  
  19.     memmove(g,f,sizeof(g));  
  20.     cout << "memmove f to g,f:" << f << endl;  
  21.     cout << "memmove f to g,g:" << g << endl;  
  22.   
  23.     cout << "diff memmove and memcopy:" << endl;  
  24.     int h[10] = {1,2,3,4,5,6,7,8,9,10};  
  25.     memmove(&h[4],h,sizeof(int)*6);  
  26.     cout << "memmove:";  
  27.     for(int i=0;i<sizeof(h)/sizeof(int);i++)  
  28.         cout << h[i] << " ";  
  29.     cout << endl;  
  30.     int j[10] = {1,2,3,4,5,6,7,8,9,10};  
  31.     memcpy(&j[4],j,sizeof(int)*6);  
  32.     cout << "memcpy:";  
  33.     for(int i=0;i<sizeof(j)/sizeof(int);i++)  
  34.         cout << j[i] << " ";  
  35.     cout << endl;  
  36. }  
  37.   
  38.   
  39.   
  40. strcpy c to d:abc  
  41. memset:33333  
  42. memcpy from e to f:33333  
  43. memmove f to g,f:33333  
  44. memmove f to g,g:33333  
  45. diff memmove and memcopy:  
  46. memmove:1 2 3 4 1 2 3 4 5 6   
  47. memcpy:1 2 3 4 1 2 3 4 1 2   
0 0