Strcpy和Strncpy的区别-

来源:互联网 发布:java 500错误原因 编辑:程序博客网 时间:2024/05/17 08:52

第一种情况:
char* p="how are you ?";
char name[20]="ABCDEFGHIJKLMNOPQRS";


strcpy(name,p); //name改变为"how are you ? OPQRS " ====>错误!
strncpy(name,p,sizeof(name)) //name改变为"how are you ? " ====>正确!

第二种情况:
char* p="how are you ?";
char name[20];

strcpy(name,p); //name改变为"how are you ? 未知字符 " ====>错误!
name[sizeof(name)-1]='/0' //和上一步组合,得到正确的结果!
strncpy(name,p,sizeof(name)); //name改变为"how are you ? " ====>正确!

第三种情况:
char* p="how are you ?";
char name[10];

strcpy(name,p); //name改变为"how are yo" ====>无结束符'/0',错误!
name[sizeof(name)-1]='/0' //和上一步组合,弥补结果。但要注意,字符传递错误!
strncpy(name,p,sizeof(name)); //和单纯的一步strcpy结果一样!

================================================
总结:strcpy
如果源长>目标长,则将源长中等于目标长的字符拷贝到目标字符串
如果源长<目标长,则源长全部拷贝到目标字符串,不包括'/0'
strncpy
如果目标长>指定长>源长,则将源长全部拷贝到目标长,自动加上'/0'
如果指定长<源长,则将源长中按指定长度拷贝到目标字符串,不包括'/0'
如果指定长>目标长,error happen!
参考资料:http://www.blog.edu.cn/user2/26497/archives/2005/306952.shtml

 

原型:extern void *memcpy(void *dest, void *src, unsigned int count);

  用法:#include <string.h>

  功能:由src所指内存区域复制count个字节到dest所指内存区域。

  说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。

  举例:

  // memcpy.c

  #include <syslib.h>

  #include <string.h>

  int main(int argc, char* argv[])

  {

  char *s="Golden Global View";

  char d[20];

  clrscr();

  memcpy(d,s,strlen(s));

  d[strlen(s)]='/0';

  printf("%s",d);

  getchar();

  return 0;

  }

  截取view

  #include <string.h>

  int main(int argc, char* argv[])

  {

  char *s="Golden Global View";

  char d[20];

  memcpy(d,s+14,4);

  //memcpy(d,s+14*sizeof(char),4*sizeof(char));也可

  d[5]='/0';

  printf("%s",d);

  getchar();

  return 0;

  }

  输出结果:

  View

  初始化数组

  char msg[10];

  memcpy(msg,0,sizeof(memcpy));

原创粉丝点击