strcpy和memcpy主要有以下3方面的区别。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy
程序例
example1
作用:将s中的字符串复制到字符数组d中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// memcpy.c
#include <stdio.h>
#include <string.h>
intmain()
{
char*s="Golden Global View";
chard[20];
clrscr();
memcpy(d,s,(strlen(s)+1));
printf("%s",d);
getchar();
return0;
}
|
输出结果:Golden Global View
example2
作用:将s中第14个字符开始的4个连续字符复制到d中。(从0开始)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#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
作用:复制后覆盖原有部分数据
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <stdio.h>
#include <string.h>
intmain(void)
{
charsrc[] ="******************************";
chardest[] ="abcdefghijlkmnopqrstuvwxyz0123as6";
printf("destination before memcpy: %s\n", dest);
memcpy(dest, src,strlen(src));
printf("destination after memcpy: %s\n", dest);
return0;
}
|
输出结果:
destination before memcpy:abcdefghijlkmnopqrstuvwxyz0123as6
destination after memcpy: ******************************as6
另二维适用
memcpy(a, b, sizeof(b));