概念:memcpy指的是c和c++使用的内存拷贝函数,memcpy函数的功能是从源内存地址的起始位置开始拷贝若干个字节到目标内存地址中。
eg1:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
char sz[] = { 0x0,0x0,0x0,0x1 };
int a;
memcpy(&a, sz, sizeof(sz));
cout<< a;
getchar();
return 0;
}
由于是一个字节一个字节拷贝,所以输出为0x10000000,十进制就为 16777216
eg2:
作用:将s中的字符串复制到字符数组d中
#include <stdio.h>
#include <string.h>
#include <iostream>
int main()
{
char* s = "GoldenGlobalView";
char d[20];
system("cls");
memcpy(d, s, (strlen(s) + 1)); //+1 是为了将字符串后面的'\0'字符结尾符放进来,去掉+1可能出现乱码
printf("%s", d);
getchar();
return 0;
}
eg3.
作用:将s中第13个字符开始的4个连续字符复制到d中。(从0开始)
#include<string.h>
#include<stdio.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;
}
eg4:
作用:复制后覆盖原有部分数据
#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);
getchar();
return 0;
}
深圳程序交流群550846167欢迎来学习讨论交流