bcopy memcpy

来源:互联网 发布:怎么安装mysql完全安装 编辑:程序博客网 时间:2024/05/18 19:21

extern void bcopy(const void *src, void *dest, int n);

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

注意它们的主要区别:dest,src使用是要特别注意

bcopy:extern void bcopy(const void *src, void *dest, int n);

  用法:#include <string.h>

  功能:将字符串src的前n个字节复制到dest中

  说明:bcopy不检查字符串中的空字节NULL,函数没有返回值。

  举例:

  // bcopy.c

  #include <syslib.h>

  #include <string.h>

  main()

  {

  char *s="Golden Global View";

  char d[20];

  clrscr(); // clear screen

  bcopy(s,d,6);

  printf("s: %s\n",s);

  printf("d: %s\n",d);

  getchar();

  clrscr();

  s[13]=0;

  bcopy(s+7,d,11); // bcopy ignore null in string

  printf("%s\n",s+7);

  for(i=0;i<11;i++)

  putchar(d);

  getchar();

  return 0;

  }

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

由src指向地址为起始地址的连续n个字节的数据复制到以dest指向地址为起始地址的空间内

1.source和destin所指内存区域不能重叠,函数返回指向destin的指针

2.与strcpy相比,memcpy并不是遇到'\0'就结束,而是一定会拷贝完n个字节。

3.如果目标数组destin本身已有数据,执行memcpy()后,将覆盖原有数据(最多覆盖n)。如果要追加数据,则每次执行memcpy后,要将目标数组地址增加到你要追加数据的地址 //注意,source和destin都不一定是数组,任意的可读写的空间均可。---wk

列举:example1

  作用:将s中的字符串复制到字符数组d中。

  // memcpy.c

  #include <stdio.h>

  #include <string.h>

  int main()

  {

  char *s="Golden Global View";

  char d[20];

  clrscr();

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

  d[strlen(s)]='\0'; //因为从d[0]开始复制,总长度为strlen(s),d[strlen(s)]置为结束符

  printf("%s",d);

 getchar();

  return 0;

  }

  输出结果:Golden Global View

example2

  作用:将s中第14个字符开始的4个连续字符复制到d中。(从0开始)

  #include <string.h>

  int main()

  {

  char *s="Golden Global View";

  char d[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();

  return 0 

  }

  输出结果: View

  example3

  作用:复制后覆盖原有部分数据

  #include <stdio.h>

  #include <string.h>

  int main(void)

  {

  char src[] = "******************************";

  char dest[] = "abcdefghijlkmnopqrstuvwxyz0123as6";

  printf("destination before memcpy: %s\n", dest);

  memcpy(dest, src, strlen(src));

  printf("destination after memcpy: %s\n", dest);

  return 0;

  }

  输出结果:

    desination before memcpy:abcdefghijlkmnopqrstuvwxyz0123as6

  destination after memcpy: ******************************as6

0 0