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