memcpy()和memmove()可以处理任意类型的数组。
void *memcoy(void * restrict s1, const void * restrict s2, size_t n);
void *memmove(void *s1, const boid *s2, size_t n);
这俩个函数都从s2指向的位置拷贝n字节到s1指向的位置,而且都返回s1的值。所不同的是,memcpy()的参数带关键字restrict,即么memcpy()假设俩个内存区域之间没有重叠;而memmove不作这样的假设,所以拷贝过程类似于先把所有的字节拷贝到一个临时缓冲区,然后再拷贝到最终目的地。如果使用memcpy()时,俩区域重叠,其行为是未定义的,这意味着该函数可能正常工作,也可能失败。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char name[20];
int age;
}student;
void showarray(const int ar[], int n);
int main()
{
int va[4] = {1, 2, 3, 4};
int vb[4];
student stu1={
"lisi",
21
};
student stu2;
student stu3;
printf("整形数组copy\n");
memcpy(vb, va, sizeof(va));
showarray(vb, 4);
printf("结构体copy\n");
memset((char *)&stu2, 0, sizeof(stu2));
memset((char *)&stu3, 0, sizeof(stu3));
memcpy(&stu2, &stu1, sizeof(stu1));
printf("stu2[%s][%d]\n", stu2.name, stu2.age);
memcpy(&stu3, &stu1, sizeof(stu1));
printf("stu3[%s][%d]\n", stu3.name, stu3.age);
return 0;
}
void showarray(const int ar[], int n)
{
int index = 0;
for(index = 0; index < n; index++)
{
printf("%d", ar[index]);
if(index % 6 == 5)
{
putchar('\n');
}
}
if(index % 6 != 1)
{
putchar('\n');
}
}