设为首页 加入收藏

TOP

第 16 章 C 预处理器和 C 库(string.h 库中的 memcpy() 和 memmove())
2018-10-21 14:13:03 】 浏览:33
Tags:处理器 string.h memcpy memmove
 1 /*-----------------------------------------
 2     mems.c -- 使用 memcpy() 和 memmove()
 3 -----------------------------------------*/
 4 
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <stdlib.h>
 8 
 9 #define SIZE 10
10 
11 void show_array(const int ar[], int n);
12 
13 int main()
14 {
15     int values[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
16     int target[SIZE];
17     double curious[SIZE / 2] = {2.0, 2.0e5, 2.0e10, 2.0e20, 2.0e30};
18 
19     puts("memcpy() used:");
20     fputs("values (original data):\n", stdout);        //等同于 puts("values (original data):");
21     show_array(values, SIZE);
22     memcpy(target, values, SIZE * sizeof(int));
23     puts("target (copy of values):");
24     show_array(target, SIZE);
25 
26     puts("\nUsing memmove() with overlapping ranges:");
27     memmove(values + 2, values, (SIZE / 2) * sizeof(int));
28     puts("values -- elements 0-4 copied to 2-6:");
29     show_array(values, SIZE);
30 
31     puts("\nUsing memcpy() to copy double to int:");
32     memcpy(target, curious, (SIZE / 2) * sizeof(double));
33     puts("target -- 5 double into 10 int positions:");
34     show_array(target, SIZE / 2);
35     show_array(target + 5, SIZE / 2);
36 
37     return 0;
38 }
39 
40 void show_array(const int ar[], int n)
41 {
42     for (int index = 0; index != n; ++index)
43         printf("%d ", ar[index]);
44 
45     fputc('\n', stdout);
46 }
mems.c

程序最后一次调用 memcpy() 从 double 类型数组中把数据拷贝到 int 类型数组中,演示了 memcpy() 函数不关心数据的类型,它只负责从一个位置把一些字节拷贝到另一个位置。而且,拷贝过程中也不会进行类型转换。如果用循环对数组中的每个元素赋值,double 类型的值会在赋值过程被转换为 int 类型的值。这种情况下,按原样拷贝字节,然后程序将这些位组合解释成 int 类型。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇第 16 章 C 预处理器和 C 库(直.. 下一篇第 17 章 高级数据表示(链表)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目