// Join items on output stream. (3.01)
#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;
const char *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(const int *a, size_t n, int end, _Bool reverse)
{
ostream_join(a, n, sizeof *a, putint, ", ", stdout, reverse);
if (end != 0)
}
int main(void)
{
int a[] = {1, 2, 3, 4};
print_ints(a, sizeof a / sizeof *a, '\n', 0);
print_ints(a, sizeof a / sizeof *a, '\n', 1);
return 0;
}
Ly8gSm9pbiBpdGVtcyBvbiBvdXRwdXQgc3RyZWFtLiAoMy4wMSkKCiNpbmNsdWRlIDxzdGRpby5oPgoKdm9pZCBvc3RyZWFtX2pvaW4oCiAgICBjb25zdCB2b2lkICpiYXNlLCBzaXplX3Qgbml0ZW1zLCBzaXplX3QgaXRlbXNpemUsCiAgICB2b2lkICgqcHV0aXRlbSkoY29uc3Qgdm9pZCAqaXRlbSwgRklMRSAqc3RyZWFtKSwKICAgIGNvbnN0IGNoYXIqIHNlcGFyYXRvciwgRklMRSAqc3RyZWFtLCBfQm9vbCByZXZlcnNlKQp7CiAgICBjb25zdCBjaGFyICpmaXJzdCA9IGJhc2U7CiAgICBjb25zdCBjaGFyICpsYXN0ID0gZmlyc3QgKyBuaXRlbXMqaXRlbXNpemU7CgogICAgaWYgKGZpcnN0ICE9IGxhc3QpIHsKICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgIGlmIChyZXZlcnNlKSB7CiAgICAgICAgICAgICAgICBsYXN0IC09IGl0ZW1zaXplOwogICAgICAgICAgICAgICAgcHV0aXRlbShsYXN0LCBzdHJlYW0pOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgcHV0aXRlbShmaXJzdCwgc3RyZWFtKTsKICAgICAgICAgICAgICAgIGZpcnN0ICs9IGl0ZW1zaXplOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmIChmaXJzdCA9PSBsYXN0KQogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGZwdXRzKHNlcGFyYXRvciwgc3RyZWFtKTsKICAgICAgICB9CiAgICB9Cn0KCi8vIFVzZS4KCnZvaWQgcHV0aW50KGNvbnN0IHZvaWQgKml0ZW0sIEZJTEUgKnN0cmVhbSkKewogICAgZnByaW50ZihzdHJlYW0sICIlZCIsICooY29uc3QgaW50ICopIGl0ZW0pOwp9Cgp2b2lkIHByaW50X2ludHMoY29uc3QgaW50ICphLCBzaXplX3QgbiwgaW50IGVuZCwgX0Jvb2wgcmV2ZXJzZSkKewogICAgcHV0Y2hhcignWycpOwogICAgb3N0cmVhbV9qb2luKGEsIG4sIHNpemVvZiAqYSwgcHV0aW50LCAiLCAiLCBzdGRvdXQsIHJldmVyc2UpOwogICAgcHV0Y2hhcignXScpOwogICAgaWYgKGVuZCAhPSAwKQogICAgICAgIHB1dGNoYXIoZW5kKTsKfQoKaW50IG1haW4odm9pZCkKewogICAgaW50IGFbXSA9IHsxLCAyLCAzLCA0fTsKICAgIHByaW50X2ludHMoYSwgc2l6ZW9mIGEgLyBzaXplb2YgKmEsICdcbicsIDApOwogICAgcHJpbnRfaW50cyhhLCBzaXplb2YgYSAvIHNpemVvZiAqYSwgJ1xuJywgMSk7CiAgICByZXR1cm4gMDsKfQ==