0

我让我的程序打印出文件中的单词,并在它们出现多次时递增。我现在只得到“NULL”,而计数为“17”。我找不到任何我改变的东西,但不确定是不是因为我还没有弄清楚如何正确释放我的数组。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BASE 5
#define MAX 50

typedef char *string;

struct wordCount 
{
string word; 
unsigned int count;
}; 

int main (void)
{
unsigned int i; 
unsigned int found; 
unsigned int arraysize; 
unsigned int newsize; 
char temp [40];  
struct wordCount* wordArray; 

FILE *infile; 
arraysize = 0; 
infile = fopen("input.txt","r");
wordArray = malloc(BASE * sizeof(struct wordCount)); 

/*store in word from infile to struct, increment counter each time it appears*/ 
while (fscanf(infile, "%s", temp) == 1) { 
    found = 0; 
    for (i = 0; i < arraysize; i++){
        if(strcmp(temp,wordArray[i].word) == 0){
            wordArray[i].count++;
            found++; 
        } 
     }
     if (found== 0){
        if (arraysize<BASE){     
            wordArray[arraysize].word = (char 
                          *)malloc((strlen(temp)+1) * sizeof(char));
            strcpy(wordArray[arraysize].word,temp); 
            wordArray[arraysize].count = 1; 
            arraysize++;  
         } else {
          wordArray = realloc(wordArray, arraysize * sizeof(struct wordCount)); 
          wordArray[arraysize].word = (char *)malloc((strlen(temp)+1) * 
                 sizeof(char));
          strcpy(wordArray[arraysize].word,temp); 
          wordArray[arraysize].count = 1; 
          arraysize++; 
        }
     }
}

fclose(infile);  
/*newsize = SearchAndDestroy(wordArray, arraysize); */

for (i = 0; i < arraysize; i++) {
    printf("%s ", wordArray[arraysize].word);
    printf("%d\n", wordArray[arraysize].count); 
    /*free(wordArray[i].word);*/
}
/* and when done:*/
free(wordArray); 

return 0; 
   }
4

1 回答 1

0

你没有正确地跟踪事情。需要注意的是,“我有多少词”、“我有多少词空间”和“我想有多少词空间”是三个不同的项目,都需要单独跟踪。特别是,看起来您的调用不realloc()正确。

于 2013-04-30T23:38:26.860 回答