fork(1) download
  1. // Join items on output stream. (2.00)
  2.  
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include <stdio.h>
  7.  
  8. // Utility.
  9.  
  10. void *xmalloc(size_t n)
  11. {
  12. void *p = malloc(n);
  13. assert(p != 0 || n == 0);
  14. return p;
  15. }
  16.  
  17. void iter_swap(void *a, void *b, size_t n)
  18. {
  19. char *x = a;
  20. char *y = b;
  21. for (size_t i = 0; i < n; i++) {
  22. char t = x[i]; x[i] = y[i]; y[i] = t;
  23. }
  24. }
  25.  
  26. void *reverse(void *base, size_t nitems, size_t itemsize)
  27. {
  28. char *first = base, *last = first + nitems*itemsize;
  29. if (first != last) {
  30. for (;;) {
  31. last -= itemsize;
  32. if (first >= last) break;
  33. iter_swap(first, last, itemsize);
  34. first += itemsize;
  35. }
  36. }
  37. return base;
  38. }
  39.  
  40. void *reverse_copy(const void *source, size_t nitems, size_t itemsize, void *dest)
  41. {
  42. return reverse(memmove(dest, source, nitems*itemsize), nitems, itemsize);
  43. }
  44.  
  45. void ostream_join(const void *base, size_t nitems, size_t itemsize,
  46. void (*putitem)(const void *item, FILE *stream),
  47. const char* separator, FILE *stream)
  48. {
  49. const char *first = base, *last = first + nitems*itemsize;
  50. if (first != last) {
  51. for (;;) {
  52. putitem(first, stream);
  53. first += itemsize;
  54. if (first == last) break;
  55. fputs(separator, stream);
  56. }
  57. }
  58. }
  59.  
  60. // Use.
  61.  
  62. void putint(const void *item, FILE *stream)
  63. {
  64. fprintf(stream, "%d", *(const int *) item);
  65. }
  66.  
  67. void print_ints(const int *a, size_t n, int end)
  68. {
  69. putchar('[');
  70. ostream_join(a, n, sizeof *a, putint, ", ", stdout);
  71. putchar(']');
  72. putchar(end);
  73. }
  74.  
  75. void print_ints_backward(const int *a, size_t n, int end)
  76. {
  77. int *temp = reverse_copy(a, n, sizeof *a, xmalloc(n * sizeof *a));
  78. print_ints(temp, n, end);
  79. free(temp);
  80. }
  81.  
  82. int main(void)
  83. {
  84. int a[] = {1, 2, 3, 4};
  85. print_ints(a, sizeof a / sizeof *a, '\n');
  86. print_ints_backward(a, sizeof a / sizeof *a, '\n');
  87. return 0;
  88. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
[1, 2, 3, 4]
[4, 3, 2, 1]