memcpy

函數原型

void *memcpy(void *dest, const void *src, size_t n);

編輯本段功能

從源src所指的內存地址的起始位置開始拷貝n個字節到目標dest所指的內存地址的起始位置中

編輯本段所需頭文件

#include <string.h>

編輯本段返回值

函數返回dest的值。

編輯本段說明

1.source和destin所指內存區域不能重疊,函數返回指向destin的指針
2.strcpy和memcpy主要有以下3方面的區別。
2.1、複製的內容不同。strcpy只能複製字符串,而memcpy可以複製任意內容,例如字符數組、整型、結構體、類等。
2.2、複製的方法不同。strcpy不需要指定長度,它遇到被複制字符的串結束符"\0"才結束,所以容易溢出。memcpy則是根據其第3個參數決定複製的長度。
2.3、用途不同。通常在複製字符串時用strcpy,而需要複製其他類型數據時則一般用memcpy
3.如果目標數組destin本身已有數據,執行memcpy()後,將覆蓋原有數據(最多覆蓋n)。如果要追加數據,則每次執行memcpy後,要將目標數組地址增加到你要追加數據的地址。
注意:source和destin都不一定是數組,任意的可讀寫的空間均可。

編輯本段程序例

example1

作用:將s中的字符串複製到字符數組d中。
// memcpy.c
#include <stdio.h>
#include <string.h>
int main()
{
char *s="Golden Global View";
char d[20];
clrscr();
memcpy(d,s,(strlen(s)+1));
printf("%s",d);
getchar();
return 0;
}
輸出結果:Golden Global View

example2

作用:將s中第14個字符開始的4個連續字符複製到d中。(從0開始)
#include <string.h>
int main()
{
char *s="Golden Global View";
char d[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();
return 0;
}
輸出結果: View

example3

作用:複製後覆蓋原有部分數據
#include <stdio.h>
#include <string.h>
int main(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;
}
輸出結果:
destination before memcpy:abcdefghijlkmnopqrstuvwxyz0123as6
destination after memcpy: ******************************as6
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章