strcpy和memcpy的區別


前一段時間,做了一段字節拷貝,結果發現用strcpy拷貝一直出錯,結果用memcpy就沒有出現問題。

具體實例如下:

1             memcpy(model_data, test_model_data, sizeof(test_model_data));

其中model_data,sony_model_data 定義為u16數組;

   static const u16 model_data[] = {0}

在linux內核中,關於這兩個函數的聲明和定義如下:

 91 /**
 92  * strcpy - Copy a %NUL terminated string
 93  * @dest: Where to copy the string to
 94  * @src: Where to copy the string from
 95  */
 96 #undef strcpy
 97 char *strcpy(char *dest, const char *src)                                                                                                                                                  
 98 {
 99         char *tmp = dest;
100 
101         while ((*dest++ = *src++) != '\0')
102                 /* nothing */;
103         return tmp;
104 }
105 EXPORT_SYMBOL(strcpy);
590 /**
591  * memcpy - Copy one area of memory to another
592  * @dest: Where to copy to
593  * @src: Where to copy from
594  * @count: The size of the area.
595  *
596  * You should not use this function to access IO space, use memcpy_toio()
597  * or memcpy_fromio() instead.
598  */
599 void *memcpy(void *dest, const void *src, size_t count)
600 {
601         char *tmp = dest;
602         const char *s = src;
603 
604         while (count--)
605                 *tmp++ = *s++;
606         return dest;
607 }
608 EXPORT_SYMBOL(memcpy)

strcpy字符串復制,不僅會復制其字符串就連其結尾的字符‘\0’也會被復制過去,其復制遇到\0后就結束了;

而memcpy就不一樣了,他是內存復制,他不僅可以復制字符串還可以復制任意內容,如字符串數組,結構體等;而且memcpy並不會遇到\0就結束,而是復制你在第三個參數中指定的字節數。

相對而言,memcpy要比strcpy用途要廣泛的多,一般我們只需要復制字符串就可以選擇strcpy,但是數組或者結構體,那就不要猶豫了,直接上memcpy吧。

 今天看到了一篇Blog,介紹了詳細的介紹了memcpy的實際用法,鏈接如下:

http://blog.csdn.net/tigerjb/article/details/6841531

把其實例粘貼出來:

程序例

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM