我應該將fp
複製到行。 我首先找到fp
中的文本長度,然後我動態地分配行並使用fgets
檢索文本。 我一直在自動平地機上收到「Your return code was -11 but it was supposed to be 0
」。這只是當然代碼的一部分。我有一個makefile和main。 我的seg故障在哪裏?將文本文件複製到數組
void read_lines(FILE* fp, char*** lines, int* num_lines){
int num_chars=0;
int index=0;
int lengths[index];
int i=0;
//find the length of the rows n cols in fp
//while there is still character in the text
while(!feof(fp)){
//get that character
char current_char= fgetc(fp);
//implement the number character
num_chars++;
//enter at the end of the first then each line
if(current_char=='\n'){
//find the length of the next line of sentence/word.
// This array stores the length of characters of each line
lengths[index]= num_chars;
//update index
index++;
// Reset the number of characters for next iteration
num_chars = 0;
// Increment the number of lines read so far
(*num_lines)++;
}
}
//now we need to copy the characters in fp to lines
(*lines)=(char**) malloc((*num_lines)*sizeof(char*));
for(i=0;i<*num_lines;i++){
(*lines)[i]=(char*)malloc(lengths[i]*sizeof(char));
fgets(*lines[i],(lengths[i]+1),fp);
fseek(fp,0,SEEK_SET);
}
}
'int index = 0; int lengths [index];'你是(使用'gcc'擴展名)分配一個零字節的數組。這會在你第一次使用它時崩潰。你是否真的在本地測試了你的代碼,而不是通過你擁有的自動平地機工具? –
與你的問題無關,但你應該確實閱讀[爲什麼是「while(!feof(file))」總是錯的?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file -always-錯誤的)。另外,['fgetc'](http://en.cppreference.com/w/c/io/fgetc)函數返回一個'int'。 –
更多與您的問題相關的負面返回代碼表示崩潰,您應該始終使用* debugger *來解決這些問題。 –