(1 函数原型
void *memcpy(void *dest, const void *src,
size_t n);
(2 功能
从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中
(3 例1
#include
#include
int main()
{
int s[20],a,d[20]={0};
for(a=0;a<=20;a++)
s[a]=a;
memcpy(d,s+14,16);
for(a=0;a<=3;a++)
printf("%d\n",d[a]);
return 0;
}
输出结果:
14
15
16
17
Process returned 0
(0x0) execution time : 0.196
s
Press any key to continue.
我不明白的是明明int占四个字节,为什么memcpy中的第二项写的是 s+14
却真的从第14项开始复制,按照定义不应该是memcpy(d,s+14*sizeof(int),4*sizeof(int)) 也就是memcpy(d,s+14*4,4*4)吗?但是试验过结果反而错了,不知道为什么╭(╯^╰)╮
。。。。
例2
#include
#include
int main()
{
char
s[30]="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);
return
0;
}
运行结果:
View
Process returned 0 (0x0) execution time : 0.699 s
Press any key to continue.
毕竟字符只占一个字节简单明了得多
PS:在《算法竞赛入门经典》一书,推荐的用法:
memcpy(b,a,sizeof(type)*k)
表示从数组a中复制k个元素到数组b