1. 程式人生 > >C函式之memcpy()函式用法

C函式之memcpy()函式用法

函式原型

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

功能

由src指向地址為起始地址的連續n個位元組的資料複製到以destin指向地址為起始地址的空間內。

標頭檔案

#include<string.h>

返回值

  函式返回一個指向dest的指標。

說明

  1.source和destin所指記憶體區域不能重疊,函式返回指向destin的指標。

  2.與strcpy相比,memcpy並不是遇到'\0'就結束,而是一定會拷貝完n個位元組。

memcpy用來做記憶體拷貝,你可以拿它拷貝任何資料型別的物件,可以指定拷貝的資料長度;

例:

  char a[100], b[50];

  memcpy(b, a,sizeof(b)); //注意如用sizeof(a),會造成b的記憶體地址溢位。

  strcpy就只能拷貝字串了,它遇到'\0'就結束拷貝;例:

  char a[100], b[50];

strcpy(a,b);

  3.如果目標陣列destin本身已有資料,執行memcpy()後,將覆蓋原有資料(最多覆蓋n)。如果要追加資料,則每次執行memcpy後,要將目標陣列地址增加到你要追加資料的地址。

  //注意,source和destin都不一定是陣列,任意的可讀寫的空間均可。

程式例

example1

  作用:將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<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

轉載來自:  http://blog.csdn.net/tigerjibo/article/details/6841531