开头
大家好,我叫这是我58。今天,我们来学一下关于C语言里的memcpy
函数的一些知识。
1.什么是memcpy
函数
memcpy
函数,是一个来自于头文件string.h
的函数,用来把一块内存拷贝到另一块内存去,适用于内存不重叠的情况,memcpy
函数是由这样构成的:void * memcpy ( void * destination, const void * source, size_t num );
1,其中,destination
代表了要粘贴的内存,course
代表了要复制的内存,而num
则代表了要拷贝的大小(单位为字节),并且,memcpy
返回的是类型为void*
的destination
,那么,为什么memcpy
函数的所有参数的类型分别是void*
,const void*
,和size_t
呢?其实啊,这是因为memcpy
这个函数的用途就是把一块内存拷贝到另一块内存去,在这期间,不用考虑类型,只要考虑内存的大小就可以了,而又为了使这个函数更有鲁棒性,所以,memcpy
函数的前两个参数的类型分别为void*
和const void*
了,并且,由于内存的大小一直不会为负数,所以,memcpy
函数的第三个参数的类型就为size_t
了。在你看到这里后,接下来就要看一下memcpy
函数的内部了。
2.memcpy
函数的内部
程序
void* memcpy(void* destination, const void* source, size_t num) {
while (num--) {
*(char*)destination = *(char*)source;
(char*)destination = (char*)destination + 1;
(char*)source = (char*)source + 1;
}
return destination;
}
流程图
3.memcpy
函数的实际应用
浮点型数组拷贝
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int main() {
int i = 0;
double arr[5] = { 1.2,2.3,3.3,4.4,5.5 };
double arra[5] = { 0 };
int isz = sizeof arr / sizeof arr[0];
memcpy(arra,arr,40);
for (; i < isz; i++) {
printf("%lf ", arra[i]);
}
return 0;
}
字符串追加自己的另一种方法
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int main() {
char str[99] = "";
scanf("%s", str);
memcpy(str + strlen(str), str, strlen(str));
printf("%s\n", str);
return 0;
}
指针数组拷贝
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int main() {
int arr[3][3] = { 1,2,3,4,5,6,76,8,91 };
int* arrp[3] = { arr[0],arr[1],arr[2] };
int* arrpa[3] = { &arr[0][1],&arr[1][1], &arr[2][1] };
int isz = sizeof arrpa / sizeof arrpa[0];
memcpy(arrpa, arrp, sizeof &arr*isz);
printf("%d %d %d\n", *(arrpa[0]), *(arrpa[1]), *(arrpa[2]));
return 0;
}
……
结尾
在你看到这里之后,可以评论来互动一下我哦。