c和c++使用的內存拷貝函數,memcpy函數的功能是從源src所指的內存地址的起始位置開始拷貝n個字節到目標dest所指的內存地址的起始位置中。
1、函數原型
void *memcpy(void *dest, const void *src, size_t n);
2、功能
從源src所指的內存地址的起始位置開始拷貝n個字節到目標dest所指的內存地址的起始位置中
3、所需頭文件
C語言中使用#include <string.h>;
C++中使用#include <cstring>和#include <string.h>都可以。
4、返回值
函數返回指向dest的指針。
5、說明
1.source和destin所指的內存區域可能重疊,但是如果source和destin所指的內存區域重疊,那么這個函數並不能夠確保source所在重疊區域在拷貝之前不被覆蓋。而使用memmove可以用來處理重疊區域。函數返回指向destin的指針.
2.如果目標數組destin本身已有數據,執行memcpy()后,將覆蓋原有數據(最多覆蓋n)。如果要追加數據,則每次執行memcpy后,要將目標數組地址增加到你要追加數據的地址。
注意:source和destin都不一定是數組,任意的可讀寫的空間均可。
6、函數實現
程序示例example1
作用:將s中的字符串復制到字符數組d中。
//memcpy.c
#include <stdio.h> #include <string.h>
int main() { char* s="GoldenGlobalView"; chard[20]; clrscr(); memcpy(d,s,(strlen(s)+1)); printf("%s",d); getchar(); return 0; }
輸出結果:Golden Global View
程序示例 example2
作用:將s中第13個字符開始的4個連續字符復制到d中。(從0開始)
#include<string.h>
int main( { char* s="GoldenGlobalView"; char d[20]; memcpy(d,s+12,4);//從第13個字符(V)開始復制,連續復制4個字符(View)
d[4]='\0';//memcpy(d,s+14*sizeof(char),4*sizeof(char));也可
printf("%s",d); getchar(); return 0; }
輸出結果:
View
程序示例 example3
作用:復制后覆蓋原有部分數據
#include<stdio.h> #include<string.h> intmain(void) { char src[]="******************************"; char dest[]="abcdefghijlkmnopqrstuvwxyz0123as6"; printf("destination before memcpy:%s\n",dest); memcpy(dest,src,strlen(src)); printf("destination after memcpy:%s\n",dest); return 0; }
輸出結果: