我让我的程序打印出文件中的单词,并在它们出现多次时递增。我现在只得到“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;
}