• 第 16 章 C 预处理器和 C 库(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):
    ", 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("
    Using 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("
    Using 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('
    ', stdout);
    46 }
    mems.c

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

  • 相关阅读:
    bzoj3993: [SDOI2015]星际战争
    bzoj3583: 杰杰的女性朋友 && 4362: Graph
    bzoj2260: 商店购物 && 4349: 最小树形图
    老oj3444 && Pku3241 Object Clustering
    bzoj3754: Tree之最小方差树
    bzoj2215: [Poi2011]Conspiracy
    老oj曼哈顿最小生成树
    bzoj2180: 最小直径生成树
    棋盘问题
    油田 Oil Deposits
  • 原文地址:https://www.cnblogs.com/web1013/p/9258741.html
Copyright © 2020-2023  润新知