memcpy使用

来源:互联网 发布:nginx跳转保持url不变 编辑:程序博客网 时间:2024/06/03 23:08

c和c++使用的内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。


函数原型:

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


示例1:将s中的字符串复制到字符数组d中。

#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;
}

示例2:将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;
}


示例3:复制后覆盖原有部分数据

#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