我应该将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 *来解决这些问题。 –