歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C函數之memcpy()函數用法

C函數之memcpy()函數用法

日期:2017/3/1 11:16:46   编辑:Linux編程

函數原型

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

Copyright © Linux教程網 All Rights Reserved