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