函數原型
void *memcpy(void*dest, const void *src, size_t n);
功能
由src指向地址爲起始地址的連續n個字節的數據複製到以destin指向地址爲起始地址的空間內。
頭文件
include
//作用:將s中的字符串複製到字符數組d中。
//memcpy.c
#include<stdio.h>
#include<string.h>
intmain()
{
char*s="Golden Global View";
chard[20];
clrscr();
memcpy(d,s,strlen(s));
d[strlen(s)]='\0';//因爲從d[0]開始複製,總長度爲strlen(s),d[strlen(s)]置爲結束符
printf("%s",d);
getchar();
return0;
}
輸出結果:GoldenGlobal View
example2
作用:將s中第14個字符開始的4個連續字符複製到d中。(從0開始)
#include<stdio.h>
#include<string.h>
intmain()
{
char*s="Golden Global View";
chard[20];
memcpy(d,s+14,4);//從第14個字符(V)開始複製,連續複製4個字符(View)
//memcpy(d,s+14*sizeof(char),4*sizeof(char));也可
d[4]='\0';
printf("%s",d);
getchar();
return0;
}
輸出結果: View
example3
作用:複製後覆蓋原有部分數據
#include<stdio.h>
#include<string.h>
intmain(void)
{
charsrc[] = "******************************";
chardest[] = "abcdefghijlkmnopqrstuvwxyz0123as6";
printf("destinationbefore memcpy: %s\n", dest);
memcpy(dest,src, strlen(src));
printf("destinationafter memcpy: %s\n", dest);
return0;
}
輸出結果:
destinationbefore memcpy:abcdefghijlkmnopqrstuvwxyz0123as6
destinationafter memcpy: ******************************as6
—————————
strcpy和memcpy主要有以下3方面的區別。
1、複製的內容不同。strcpy只能複製字符串,而memcpy可以複製任意內容,例如字符數組、整型、結構體、類等。
2、複製的方法不同。strcpy不需要指定長度,它遇到被複制字符的串結束符”\0”才結束,所以容易溢出。memcpy則是根據其第3個參數決定複製的長度。
3、用途不同。通常在複製字符串時用strcpy,而需要複製其他類型數據時則一般用memcpy