2016-11-21 74 views
0

我應該將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); 
     } 
    } 
+2

'int index = 0; int lengths [index];'你是(使用'gcc'擴展名)分配一個零字節的數組。這會在你第一次使用它時崩潰。你是否真的在本地測試了你的代碼,而不是通過你擁有的自動平地機工具? –

+4

與你的問題無關,但你應該確實閱讀[爲什麼是「while(!feof(file))」總是錯的?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file -always-錯誤的)。另外,['fgetc'](http://en.cppreference.com/w/c/io/fgetc)函數返回一個'int'。 –

+1

更多與您的問題相關的負面返回代碼表示崩潰,您應該始終使用* debugger *來解決這些問題。 –

回答

0

我看到兩個問題,這裏。

首先,長度靜態分配零字節。這可以,永遠不會工作。您將需要創建一個最大大小的長度數組(例如,最多256行)或將長度設置爲鏈接列表,以便它可以隨索引一起增長。或者,您可以在文件中進行兩次傳遞 - 一次獲取行數(在分配行數組之後),一次獲取每行的字符數。其次,雖然它是一個挑逗,但是通過從while循環中刪除num_lines,可以大大簡化代碼。循環後,只需設置

*num_lines = index; 
+0

它的作品,謝謝! –

0

段錯誤的原因是你逝去的行錯路指針

fgets(*lines[i],(lengths[i]+1),fp); 

正確的方法是: -

fgets((*lines)[i],(lengths[i]+1),fp); 
0

修復這樣

void read_lines(FILE *fp, char ***lines, int *num_lines){ 
    int num_chars=0; 
    /* int index=0; int lengths[index];//lengths[0] is bad. */ 
    int ch, i = 0, max_length = 0; 

    while((ch=fgetc(fp))!=EOF){//while(!feof(fp)){ is bad. Because it loops once more. 
     num_chars++; 
     if(ch == '\n'){ 
      ++i;//count line 
      if(num_chars > max_length) 
       max_length = num_chars; 
      //reset 
      num_chars = 0; 
     } 
    } 
    if(num_chars != 0)//There is no newline in the last line 
     ++i; 
    *num_lines = i; 

    rewind(fp);//need Need rewind 
    char *line = malloc(max_length + 1); 
    *lines = malloc(*num_lines * sizeof(char*)); 
    for(i = 0; i < *num_lines; i++){ 
     fgets(line, max_length+1, fp); 
     (*lines)[i] = malloc(strlen(line)+1); 
     strcpy((*lines)[i], line); 
    } 
    free(line); 
} 
相關問題