嗨,大家好我想实现一些课程的拼写检查,但我是新来的C和只加载字典文件是毁了我的头。下面的代码编译得很好,但运行时崩溃。有时打印500行后有时会打印1500行,但我不知道是什么原因造成的!字典文件崩溃,但编译好
#include <string.h>
#include <stdio.h>
#include <malloc.h>
int main(int argc, char *argv[])
{
FILE *words_ptr; //pointer for words.txt
char new_word[100];
char temp_word[100];
char *dict[45440];
words_ptr = fopen("dictionary.txt", "r");
if(words_ptr != NULL)
{
printf("File dictionary.txt opened\n");
int i = 0;
while (fgets(temp_word, 45440, words_ptr))
{
new_word[i] = (char)calloc(strlen(temp_word), sizeof(char)); //ensuring new_word will be the right size
strcpy(new_word, temp_word); //copy contents of temp_word to new_word
dict[i] = new_word; //copy contents of new_word to i'th element of dict array
printf("printing out dict[%d]: %s\n", i, dict[i]);
i++;
}
printf("printing out dictionary1: %s\n", dict[1]);
fclose(words_ptr);
return 0;
}
else {printf("Unable to open file words.txt\n"); return 1;}
}
* new_word [i] =(char)calloc(strlen(temp_word),sizeof(char)); //确保new_word的大小合适*不正确。 'new_word'是一个字节太小 - 你忘记了终止'\ 0'字符的空间。 –
注意:不要在C中抛出'calloc'&friends或'void *'的结果' – Olaf
'fgets(temp_word,45440,words_ptr)'→'fgets(temp_word,100,words_ptr)' –