Chapter 16 C Preprocessor and C Library (memcpy() and memmove())

Keywords: C

 1 /*-----------------------------------------
 2     mems.c -- Use memcpy() and 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);        //Equate to 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

The last time the program calls memcpy() to copy data from a double type array to an int type array, it demonstrates that the memcpy() function does not care about the type of data, it only copies some bytes from one location to another. Also, type conversion is not performed during copying. If each element in the array is assigned with a loop, the value of double type is converted to the value of int type in the assignment process. In this case, bytes are copied as they are, and the program interprets these bits as int.

Posted by vladibo on Mon, 04 Feb 2019 19:12:16 -0800