From 4e4ef99b1f7257e4fc10075bdc03196ed31cbdee Mon Sep 17 00:00:00 2001 From: Abigail Date: Fri, 22 Jan 2021 12:56:35 +0100 Subject: We only need one pointer. There's no need for a different pointer when searching for the beginning of the word, nor do we need strcpy to extract words before printing it. Instead, we set the first white space after a word to '\0', walk the pointer to the beginning of the word, then print it. --- challenge-096/abigail/c/ch-1.c | 42 ++++++++++++++---------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/challenge-096/abigail/c/ch-1.c b/challenge-096/abigail/c/ch-1.c index 36ec37d5fb..b01e726173 100644 --- a/challenge-096/abigail/c/ch-1.c +++ b/challenge-096/abigail/c/ch-1.c @@ -8,63 +8,49 @@ # include # include -# include # include int main (void) { char * line = NULL; size_t len = 0; - size_t strlen; + size_t ptr; - while ((strlen = getline (&line, &len, stdin)) != -1) { - char * line_ptr = line; - size_t end = strlen; - size_t begin; + while ((ptr = getline (&line, &len, stdin)) != -1) { size_t output = 0; - while (end > 0) { + while (ptr > 0) { /* * Skip tailing whitespace */ - while (end > 0 && isspace (line [end - 1])) { - end --; + while (ptr > 0 && isspace (line [ptr - 1])) { + ptr --; } /* - * 'end' now just after the end of a word, or + * 'ptr' is now just after the end of a word, or * at the beginning of the string; if the latter, * there is nothing left to print. */ - - if (end <= 0) { + if (ptr <= 0) { break; } /* - * Find the beginning of a word + * Terminate the string just after the newly found word */ - begin = end - 1; - while (begin > 0 && !isspace (line [begin - 1])) { - begin --; - } + line [ptr] = '\0'; /* - * Extract the word out of the string: allocate memory, - * and copy the right part of the input. + * Find the beginning of that word */ - char * word; - if ((word = malloc ((end - begin + 1) * sizeof (char))) == NULL) { - fprintf (stderr, "Out of memory\n"); - exit (1); + while (ptr > 0 && !isspace (line [ptr - 1])) { + ptr --; } - stpncpy (word, line + begin, end - begin); /* - * Print the string, prepended (except the first printed word) + * Print the word, prepended (except the first printed word) * by a space. */ - printf ("%s%s", output ++ ? " " : "", word); - - end = begin; + printf ("%s%s", output ++ ? " " : "", &line [ptr]); } printf ("\n"); } -- cgit