/* words3.c * * A (largish) input buffer takes the input, * then once the word size is known, the space * for that word is allocated on the heap. * * The list of words is stored in the stack * as a (fixed size) list of pointers. * * The heap memory is not freed until the program exits. * * $ gcc words3.c -o words3 * $ ./words3 * Input your words, one per line, with a blank line to stop. * > one * > two * > three * > * The words are ['one', 'two', 'three']. * Done. * * Jim Mahoney | Feb 2013 | MIT License */ #include #include #include #define MAX_INPUT 100 #define MAX_WORDS 10 // Read a word into the input buffer. // Then allocate memory on the heap for that word, // copy it over, and return a pointer to it. char* read_word(char* buffer){ char* status = fgets(buffer, MAX_INPUT, stdin); char* word; int length; if (status == NULL){ printf("READ ERROR - fgets returned NULL\n"); exit(1); } length = strlen(buffer); if (buffer[length - 1] == '\n'){ // remove trailing newline buffer[length - 1] = (char) 0; length--; } word = malloc(length + 1); // new memory (+1 for trailing 0) strcpy(word, buffer); // copy input to new string return word; } int main(){ char buffer[MAX_INPUT]; // input space for one word char* list[MAX_WORDS]; // list of pointers int n, i; printf("Input your words, one per line, with a blank line to stop.\n"); n = 0; // current word (i.e. row) index while (n < MAX_WORDS){ printf("> "); list[n] = read_word(buffer); if (strlen(list[n]) == 0) break; // blank line stops reading n++; } printf("The words are ["); for (i=0; i < n; i++){ printf("'%s'", list[i]); if (i != n - 1) printf(", "); } printf("].\nDone.\n"); return 0; }