Awesome, thanks. I don't know how that * got before sizeof(char). One more problem before I call this resolved:
I'm supposed to let the size of the array grow after it reaches INITIAL_SIZE, but I'm screwing up the reallocation somehow. Any ideas?:
Code:#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> const int INITIAL_SIZE = 5; typedef struct { char *word; int count; } WordBank; main() { // define local variables: WordBank *words, *tmp; char *word; int c, currentWord = 0; int i, index; words = (WordBank *) calloc (INITIAL_SIZE, sizeof (WordBank)); word = (char *) calloc (25, sizeof (char)); // get input: c = getchar(); while (c != EOF) { // if the character is a space, replace it with \n if (isspace(c) || c == '\0') { if (currentWord > (INITIAL_SIZE - 1)) { if ((tmp = realloc(words, sizeof(WordBank) * (currentWord))) == NULL) { fprintf(stderr, "Reallocation failed."); } words = tmp; free(tmp); } words[currentWord].word = (char *) calloc(strlen(word) + 1, sizeof(char)); strcpy(words[currentWord].word, word); words[currentWord].count = 1; // increment the word counter: currentWord++; strcpy(word, "\0"); // if the character is punctuation, replace it with null } else if (ispunct(c)) { c = '\0'; } else { //word = word + c; strcat(word, (char*)&c); } // grab the next character: c = getchar(); } for (i = 0; i < currentWord; i++) { printf("%s\n", words[i].word); } free(words); }




Reply With Quote