/* Sample input: A partridge in a pear tree. Two turtle doves. Three french hens. Four calling birds. Five golden rings. Some standard library functions used here: printf("%s",...) realloc() strlen() strcpy() strcat() fprintf(stderr,...) Make sure you understand how ds_getline() works. */ #include #include #include void ds_print(char **p,int *q) { if (*p) printf("%s",*p); } int ds_copy(char **p,int *q,const char *s) { int len; char *y; len = strlen(s) + 1; if (*q < len) { len += len / 8; y = realloc(*p,len); if (!y) return 0; *p = y; *q = len; } strcpy(*p,s); return 1; } int ds_concat(char **p,int *q,const char *s) { int len; char *y; if (!*p) return ds_copy(p,q,s); len = strlen(*p) + strlen(s) + 1; if (*q < len) { len += len / 8; y = realloc(*p,len); if (!y) return 0; *p = y; *q = len; } strcat(*p,s); return 1; } int ds_getline(char **p,int *q) { char s[2]; if (!ds_copy(p,q,"")) return 0; for (;;) { if (scanf("%c",s) < 1) return 1; if (!*s) *s = '\n'; /* treat 0 in input as if it were \n */ s[1] = 0; if (!ds_concat(p,q,s)) return 0; if (*s == '\n') return 1; } } void die_nomem(void) { fprintf(stderr,"dsrev: fatal: out of memory\n"); exit(111); } int main(void) { char *x = 0; /* current line */ int xspace = 0; char *y = 0; /* all previous lines, in reverse order */ int yspace = 0; if (!ds_copy(&y,&yspace,"")) die_nomem(); for (;;) { if (!ds_getline(&x,&xspace)) die_nomem(); if (!*x) return 0; /* !*x from ds_getline() means end of input */ if (!ds_concat(&x,&xspace,y)) die_nomem(); ds_print(&x,&xspace); if (!ds_copy(&y,&yspace,x)) die_nomem(); } }