//拷贝数组元素
//void *memcpy(void * restrict s1, const void * restrict s2, size_t n);
//移动数组元素
//void *memmove(void *s1, const void *s2, size_t n);
上面两个函数都从s2指向的位置拷贝n字节到s1指向的位置,而且返回s1的值。所不同的是,memcpy()的参数带关键字restrict,即memcpy()假设两个内存区域之间没有重叠; 而memmove()不作这样的假设,所以拷贝过程类似于先把所有字节拷贝到一个临时缓冲区,然后再拷贝到最终目的地。如果使用memcpy()时,两区域出现重叠,其行为是未定义的,这意味着该函数可能正常工作,也可能失败。编译器不会在本不该使用memcpy()时禁止你使用,作为程序员,在使用该函数时有责任确保两个区域不重叠。由于这两个函数设计用于处理任何数据类型,所有它们的参数都是两个指向void的指针。C允许把任何类型的指针赋给void*类型的指针
示例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //C99特性
//memcpy()、memmove()
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <tgmath.h>
#include <limits.h>
#define SIZE 10
void show_array(const int ar [], int n);
//_Static_assert(sizeof(double) == 2 * sizeof(int), "double not twice int size");
int main(int argc, char* argv[])
{
int values[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target[SIZE];
double curious[SIZE / 2] = { 2.0, 2.0e5, 2.0e10, 2.0e20, 5.0e30 };
puts("memcpy() used:");
puts("values (original data): ");
show_array(values, SIZE);
memcpy(target, values, SIZE * sizeof(int));
puts("target (copy of values): ");
show_array(target, SIZE);
puts("\nUsing memmove() with overlapping ranges:");
memmove(values + 2, values, 5 * sizeof(int));
puts("values -- elements 0-4 copied to 2-6:");
show_array(values, SIZE);
puts("\nUsing memcpy() to copy double to int:");
memcpy(target, curious, (SIZE / 2) * sizeof(double));
puts("target -- 5 doubles into 10 int positions:");
show_array(target, SIZE / 2);
show_array(target + 5, SIZE / 2);
system("pause");
return 0;
}
void show_array(const int ar[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", ar[i]);
putchar('\n');
}