zoukankan      html  css  js  c++  java
  • 第 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 类型。

  • 相关阅读:
    MyEclipse10.0构建maven web项目
    maven安装与配置(windows系统)
    Spring远程服务(RPC)
    Spring Security
    Spring MVC
    spring事务管理
    java图形界面
    Mysql 临时表+视图
    python_控制台输出带颜色的文字方法
    [Python] 字符串加密解密
  • 原文地址:https://www.cnblogs.com/web1013/p/9258741.html
Copyright © 2011-2022 走看看