概念: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歡迎來學習討論交流