memcpy函数的作用

memcpy(d,s,(strlen(s)+1));
作用:将s中的字符串复制到字符数组d中。

//memcpy.c
#include <stdio.h>
#include <string.h>
int main()
{
    char* s="GoldenGlobalView";
    char d[20];
    clrscr();
    memcpy(d,s,(strlen(s)+1));
    printf("%s",d);
    getchar();
    return 0;
}
输出结果:Golden Global View
example2
作用:将s中第13个字符开始的4个连续字符复制到d中。(从0开始)

	
#include<string.h>
int main(
{
    char* s="GoldenGlobalView";
    char d[20];
    memcpy(d,s+12,4);//从第13个字符(V)开始复制,连续复制4个字符(View)
    d[4]='\0';//memcpy(d,s+12*sizeof(char),4*sizeof(char));也可
    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;
}
输出结果:
destination before memcpy:abcdefghijlkmnopqrstuvwxyz0123as6
destination after memcpy: ******************************as6
区别
编辑
strcpy和memcpy主要有以下3方面的区别。
1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy



  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值