我正在處理的代碼讀取45430個字的字典,然後將每個字中包含的字典中的所有其他字打印到文件中。我只是將獲取文件MyDictionary txt文件讀入字符數組字[45430] [30],然後將其打印到單詞txt文件中。當我這樣做時,我在44946字處遇到seg故障,但是在同一循環中,我也正在打印到控制檯,並且所有單詞都能正確打印出來。爲什麼我在寫這個文件時遇到這個seg錯誤?爲什麼沒有seg錯誤寫入控制檯?將字典的內容寫入文件時出現分段錯誤
代碼:
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <string.h>
//char ***alloc_array(int,int);
int main(void){
FILE *fr; //declare file read file pointer
FILE *fp; //declare file printed file pointer
//char array to read in up to 30 chars
char line[31];
long numwords=45430; //number of words in dictionary
int maxlength=31; // the longest string in dictionary (30 chars)
long i; //counts up to 45430
//allocate space for 45430 words at a max length of 30 chars (1 extra char for "\0")
char ***word = calloc(numwords, sizeof(char **));
for(i = 0; i != numwords; i++) {
word[i] = calloc(maxlength, sizeof(char *));
}
//Open MyDictionary.txt and determine if there is an error or not
fr = fopen ("MyDictionary.txt", "r"); // open the file for reading
if(fr==NULL){
printf("\nError! opening input file");
exit(1); //Program exits if file pointer returns NULL.
}
//Open words-within-words.txt and determine if there is an error or not
fp = fopen ("words-within-words.txt", "w"); // open the file for reading
if(fp==NULL){
printf("\nError! opening output file");
exit(1); //Program exits if file pointer returns NULL.
}
int j=0; //counts to 30 for max length
i=0;
while(fgets(line, 40, fr) != NULL){ //get a line, up to 40 chars from fr and put first . done if NULL
for(j=0;j<30;){
word[i][j]=&line[j];
j++;
}
j=0;
printf("\n%s",word[i][j]); //print out each word of dictionary to console on its own line
/*
if((i>4 && i<8)||(i>45428)){
fprintf(fp,"\nanalyze:word[i][0]=%s\tword[i][2]=%s\ti=%li",word[i][0],word[i][2],i+1);
}
*/
fprintf(fp,"%s",word[i][j]); //print out each word of dictionary to words-in-words on its own line
i++;
}
fclose(fr); //close the files prior to exiting
fclose(fp);
return 0;
} //main
對於我的任務,我實際上需要詞的形式。字[num_words_in_dict] [length_longest]。我相信這個想法是這樣的,一旦我學會了如何將所有文字打印到文件中,就可以更容易地找到單詞中的單詞。謝謝 – user2985363
正確。然而,'strcpy()'可能會溢出目標,因爲它比源短10個字節。 – alk