您的位置:首页 > 其它

memcpy 详解

2015-08-14 08:15 399 查看

memcpy

头文件:#include<string.h>

函数原型:void *memcpy(void str,const void *s,size_t n);

功能 c和c++使用的内存拷贝函数.从源s所指的内存地址的起始位置开始拷贝n个字节到目标str所指的内存地址的起始位置中

memcpy与strcpy有以下不同:

1.复制内容不同。strcpy复制字符串,而memcpy复制字符数组、整型、结构体、类等。

2.复制方法不同。strcpy遇到被复制字符串的'\0'结束,memspy由第三个参数决定复制的长度。

example one:

[cpp] view
plaincopy





//将s中的字符串复制到字符数组str中

#include<cstdio>

#include<cstring>

int main()

{

char *s="abcd efg hi";

char str[20];

memcpy(str,s,strlen(s));

printf("%s\n",str);//输出abcd efg hi

}

example two:

[cpp] view
plaincopy





//将s中的下标为3个字符开始的连续8个字符复制到str中。

#include<cstdio>

#include<cstring>

int main()

{

char *s="abcdefg higk lmn";

char str[20];

memcpy(str,s+3,8);

str[8]='\0';

printf("%s\n",str);//输出defg hig

}

example three:

[cpp] view
plaincopy





//复制后覆盖原有的部分

#include<cstdio>

#include<cstring>

int main()

{

char s[20]="*******";

char str[20]="abcdefghigk";

memcpy(str,s,strlen(s));

printf("%s\n",str);//输出*******higk

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: