// Join items on output stream. (2.00)
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
// Utility.
void *xmalloc(size_t n)
{
return p;
}
void iter_swap(void *a, void *b, size_t n)
{
char *x = a;
char *y = b;
for (size_t i = 0; i < n; i++) {
char t = x[i]; x[i] = y[i]; y[i] = t;
}
}
void *reverse(void *base, size_t nitems, size_t itemsize)
{
char *first = base, *last = first + nitems*itemsize;
if (first != last) {
for (;;) {
last -= itemsize;
if (first >= last) break;
iter_swap(first, last, itemsize);
first += itemsize;
}
}
return base;
}
void *reverse_copy(const void *source, size_t nitems, size_t itemsize, void *dest)
{
return reverse
(memmove(dest
, source
, nitems
*itemsize
), nitems
, itemsize
); }
void ostream_join(const void *base, size_t nitems, size_t itemsize,
void (*putitem)(const void *item, FILE *stream),
const char* separator, FILE *stream)
{
const char *first = base, *last = first + nitems*itemsize;
if (first != last) {
for (;;) {
putitem(first, stream);
first += itemsize;
if (first == last) break;
fputs(separator
, stream
); }
}
}
// Use.
void putint(const void *item, FILE *stream)
{
fprintf(stream
, "%d", *(const int *) item
); }
void print_ints(const int *a, size_t n, int end)
{
ostream_join(a, n, sizeof *a, putint, ", ", stdout);
}
void print_ints_backward(const int *a, size_t n, int end)
{
int *temp = reverse_copy(a, n, sizeof *a, xmalloc(n * sizeof *a));
print_ints(temp, n, end);
}
int main(void)
{
int a[] = {1, 2, 3, 4};
print_ints(a, sizeof a / sizeof *a, '\n');
print_ints_backward(a, sizeof a / sizeof *a, '\n');
return 0;
}
Ly8gSm9pbiBpdGVtcyBvbiBvdXRwdXQgc3RyZWFtLiAoMi4wMCkKCiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0cmluZy5oPgojaW5jbHVkZSA8YXNzZXJ0Lmg+CiNpbmNsdWRlIDxzdGRpby5oPgoKLy8gVXRpbGl0eS4KCnZvaWQgKnhtYWxsb2Moc2l6ZV90IG4pCnsKICAgIHZvaWQgKnAgPSBtYWxsb2Mobik7CiAgICBh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