我的程序编译但我没有正确使用指针和realloc。我试过看其他例子,但我似乎无法将其翻译成我自己的程序。程序的要点是从文件中读取单词并在计数出现多次时递增计数。一旦结构数组遍布我的基础(5),我想重新分配空间,复制数组,然后添加下一个单词。
非常感谢任何帮助!
#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 incremented;
unsigned int j;
char temp [40];
struct wordCount wordArray[BASE];
struct wordCount *holder;
FILE *infile;
j = 0;
infile = fopen("input.txt","r");
while (fscanf(infile, "%s", temp) == 1) {
incremented = 0;
for (i = 0; i < j; i++){
if(strcmp(temp,wordArray[i].word) == 0){
wordArray[i].count++;
incremented++;
}
}
if (incremented == 0){
if (j<BASE){
wordArray[j].word = (char *)malloc((strlen(temp)+1) *
sizeof(char));
strcpy(wordArray[j].word,temp);
wordArray[j].count = 1;
j++;
} else {
holder = realloc(wordArray, sizeof(wordArray) +1);
*wordArray = *holder;
wordArray[j].word = (char *)malloc((strlen(temp)+1) * sizeof(char));
strcpy(wordArray[j].word,temp);
wordArray[j].count = 1;
j++;
}
}
}
fclose(infile);
/* bring in next file*/
/*delete du plicates */
/*sort*/
for (i = 0; i < j; i++) {
printf("%s ", wordArray[i].word);
printf("%d\n", wordArray[i].count);
}
/* and when done:*/
for(i = 0; i < j; i++){
free(wordArray[i].word);
}
return 0;
}
答案 0 :(得分:3)
这是你出错的最明显的地方:
holder = realloc(wordArray, sizeof(wordArray) +1);
中的这一行
void * realloc(void * ptr,size_t size);
...
除非ptr为NULL,否则必须由之前调用malloc(),calloc()或realloc()返回。
您的wordArray
是一个静态分配的数组,它不是通过malloc()
或朋友动态分配的。