2013-04-30 22 views
0

我的程序打印出文件中的單詞,並且當它們出現多次時遞增。我現在變得只是「NULL」而計數爲「17」。我找不到任何改變,但不知道是否因爲我沒有想出如何正確釋放我的陣列。在我的c數組中獲得空值,釋放不當

#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; 
    } 

回答

0

你沒有正確地跟蹤事情。你需要更多地關注「我有多少單詞」,「我有多少空間」以及「我希望有多少空間」等三個不同的項目,這些都是需要的分開跟蹤。特別是,它看起來不像您致電realloc()的電話是正確的。

相關問題