mems.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // mems.c -- using memcpy() and memmove()
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #define SIZE 10
  6. void show_array(const int ar[], int n);
  7. // remove following if C11 _Static_assert not supported
  8. _Static_assert(sizeof(double) == 2 * sizeof(int), "double not twice int size");
  9. int main()
  10. {
  11. int values[SIZE] = {1,2,3,4,5,6,7,8,9,10};
  12. int target[SIZE];
  13. double curious[SIZE / 2] = {2.0, 2.0e5, 2.0e10, 2.0e20, 5.0e30};
  14. puts("memcpy() used:");
  15. puts("values (original data): ");
  16. show_array(values, SIZE);
  17. memcpy(target, values, SIZE * sizeof(int));
  18. puts("target (copy of values):");
  19. show_array(target, SIZE);
  20. puts("\nUsing memmove() with overlapping ranges:");
  21. memmove(values + 2, values, 5 * sizeof(int));
  22. puts("values -- elements 0-5 copied to 2-7:");
  23. show_array(values, SIZE);
  24. puts("\nUsing memcpy() to copy double to int:");
  25. memcpy(target, curious, (SIZE / 2) * sizeof(double));
  26. puts("target -- 5 doubles into 10 int positions:");
  27. show_array(target, SIZE/2);
  28. show_array(target + 5, SIZE/2);
  29. return 0;
  30. }
  31. void show_array(const int ar[], int n)
  32. {
  33. int i;
  34. for (i = 0; i < n; i++)
  35. printf("%d ", ar[i]);
  36. putchar('\n');
  37. }