// Join items on output stream. (3.00)
#include <stdio.h>
void ostream_join(
const void *base, size_t nitems, size_t itemsize,
void (*putitem)(const void *item, FILE *stream),
const char* separator, FILE *stream, _Bool reverse)
{
const char *first = base, *last = first + nitems*itemsize;
if (first != last) {
for (;;) {
if (reverse) {
last -= itemsize;
putitem(last, stream);
} else {
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_backward(const int *a, size_t n, int end)
{
ostream_join(a, n, sizeof *a, putint, ", ", stdout, 1);
}
int main(void)
{
int a[] = {1, 2, 3, 4};
print_ints_backward(a, sizeof a / sizeof *a, '\n');
return 0;
}
Ly8gSm9pbiBpdGVtcyBvbiBvdXRwdXQgc3RyZWFtLiAoMy4wMCkKCiNpbmNsdWRlIDxzdGRpby5oPgoKdm9pZCBvc3RyZWFtX2pvaW4oCiAgICBjb25zdCB2b2lkICpiYXNlLCBzaXplX3Qgbml0ZW1zLCBzaXplX3QgaXRlbXNpemUsCiAgICB2b2lkICgqcHV0aXRlbSkoY29uc3Qgdm9pZCAqaXRlbSwgRklMRSAqc3RyZWFtKSwKICAgIGNvbnN0IGNoYXIqIHNlcGFyYXRvciwgRklMRSAqc3RyZWFtLCBfQm9vbCByZXZlcnNlKQp7CiAgICBjb25zdCBjaGFyICpmaXJzdCA9IGJhc2UsICpsYXN0ID0gZmlyc3QgKyBuaXRlbXMqaXRlbXNpemU7CiAgICBpZiAoZmlyc3QgIT0gbGFzdCkgewogICAgICAgIGZvciAoOzspIHsKICAgICAgICAgICAgaWYgKHJldmVyc2UpIHsKICAgICAgICAgICAgICAgIGxhc3QgLT0gaXRlbXNpemU7CiAgICAgICAgICAgICAgICBwdXRpdGVtKGxhc3QsIHN0cmVhbSk7CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICBwdXRpdGVtKGZpcnN0LCBzdHJlYW0pOwogICAgICAgICAgICAgICAgZmlyc3QgKz0gaXRlbXNpemU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGZpcnN0ID09IGxhc3QpIGJyZWFrOwogICAgICAgICAgICBmcHV0cyhzZXBhcmF0b3IsIHN0cmVhbSk7CiAgICAgICAgfQogICAgfQp9CgovLyBVc2UuCgp2b2lkIHB1dGludChjb25zdCB2b2lkICppdGVtLCBGSUxFICpzdHJlYW0pCnsKICAgIGZwcmludGYoc3RyZWFtLCAiJWQiLCAqKGNvbnN0IGludCAqKSBpdGVtKTsKfQoKdm9pZCBwcmludF9pbnRzX2JhY2t3YXJkKGNvbnN0IGludCAqYSwgc2l6ZV90IG4sIGludCBlbmQpCnsKICAgIHB1dGNoYXIoJ1snKTsKICAgIG9zdHJlYW1fam9pbihhLCBuLCBzaXplb2YgKmEsIHB1dGludCwgIiwgIiwgc3Rkb3V0LCAxKTsKICAgIHB1dGNoYXIoJ10nKTsKICAgIHB1dGNoYXIoZW5kKTsKfQoKaW50IG1haW4odm9pZCkKewogICAgaW50IGFbXSA9IHsxLCAyLCAzLCA0fTsKICAgIHByaW50X2ludHNfYmFja3dhcmQoYSwgc2l6ZW9mIGEgLyBzaXplb2YgKmEsICdcbicpOwogICAgcmV0dXJuIDA7Cn0=