/* words2.c * * This time memory is allocated as a "character matrix" : * one [[ 'o', 'n', 'e'], * two [ 't', 'w', 'o'] * three [ 't', 'h', 'r', 'e', 'e']] * * For string input, fgets is safe since it can set a limit on * the number of characters - thus avoiding buffer overflows. * However, it includes the newline character as part of * the input string. * * $ gcc words2.c -o words2 * $ ./words2 * 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 /* printf, fgets */ #include /* strlen */ #include /* EXIT_FAILURE */ #define MAX_WORD_SIZE 20 #define MAX_WORDS 10 #define MAX_INPUT 100 void read_word(char* string){ char* status = fgets(string, MAX_WORD_SIZE, stdin); int length; if (status == NULL){ printf("READ ERROR - fgets returned NULL\n"); exit(EXIT_FAILURE); } length = strlen(string); if (string[length - 1] == '\n'){ // remove trailing newline string[length - 1] = (char) 0; } } int main(){ char matrix[MAX_WORDS][MAX_WORD_SIZE]; // character matrix char* word; // pointer to current word int n, i; // debugging & analyzing ; change to (1) to see output. if (0){ printf("--- looking at addresses ---\n"); printf(" char matrix[%d][%d]; \n", MAX_WORDS, MAX_WORD_SIZE); printf("\n"); printf(" matrix = %p\n", matrix); // pointer to matrix printf("\n"); printf(" matrix[0] = %p\n", matrix[0]); // pointer to row 0 printf(" matrix[1] = %p\n", matrix[1]); // pointer to row 1 printf("\n"); printf(" &matrix[0][0] = %p \n", &matrix[0][0]); // address of row 0, col 0 printf(" &matrix[0][1] = %p \n", &matrix[0][1]); // address of row 0, col 1 printf(" &matrix[1][0] = %p \n", &matrix[1][0]); // address of row 1, col 0 printf("-----------------------------\n"); } 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("> "); read_word(matrix[n]); if (strlen(matrix[n]) == 0) break; // blank line to stop reading n++; } printf("The words are ["); for (i=0; i < n; i++){ printf("'%s'", matrix[i]); if (i != n - 1) printf(", "); } printf("].\nDone.\n"); return 0; }