我遇到了分段错误问题C

问题描述:

我试图打开一个文件,看看文件中有多少行,单词,字符和句子。一切都编译好,但程序运行时,它会打印指令,然后出现“分段错误(核心转储)”错误。我知道该文件打开正常,所以我猜我在processFile中做错了什么。帮助会很棒!我遇到了分段错误问题C

P.S.将#include“lib09.h”都是三个功能后的main()

#include <stdio.h> 
#include <stdlib.h> 
#include "lib09.h" 

int main(void) 
{ 
    FILE *fileIn; 
    int *lines = 0, 
     *words = 0, 
     *sentences = 0, 
     *characters = 0; 


    printInstructions(); 

    fileIn = fopen("input09.txt", "r"); 

    if (fileIn == NULL) 
     { 
     printf("\n\nERROR\n"); 
     printf("FILE DOES NOT EXIST.\n"); 
     printf("TRY AGAIN\n\n"); 
     } 

    else 
     { 
     processFile(fileIn); 
     printReport(lines, words, characters, sentences); 
     } 

    return 0; 
} 

// 
//Prints Instructions 
// 
void printInstructions() 
{ 
    printf("\n====================================================\n"); 
    printf(" Program reads a file and returns the number of \n"); 
    printf("lines, words, characters, and sentences in the file.\n"); 
    printf("====================================================\n\n"); 

    return; 
} 

// 
//Processes File 
// 
int processFile(FILE *fileIn) 
{ 
     int ch, 
     *lines = 0, 
     *sentences = 0, 
     *characters = 0, 
     *words = 0; 

    while(fscanf(fileIn, "%d", &ch) != EOF) 
    { 
     ch = fgetc(fileIn); 

       if(ch == '\n' || ch == 60) 
         return *lines++; 

       if(ch == '.') 
         return *sentences++; 

       if(ch != ' ' || ch != '.' || ch != '\n') 
         return *characters++; 

       if(ch == ' ') 
         return *words++; 
    } 

    fclose(fileIn); 

    return 0; 
} 

// 
//Prints Values from File 
// 
void printReport(int *words, int *lines, int *characters, int *sentences) 
{ 
    printf("This file contains %d lines.\n", *lines); 
    printf("This file contains %d words.\n", *words); 
    printf("This file contains %d characters.\n", *characters); 
    printf("This file contains %d sentences.\n\n", *sentences); 

    return; 
} 
+1

你在你的'processFile()'函数写四种不同的空指针。很确定您打算将这些作为地址输入参数传递给函数,并将'&var'参数传递回调用方。当然,函数本身是错误的,因为无论如何,它将错误地返回任何字符被处理的时刻。我不认为,鉴于函数的名称*任何*这些'return'语句应该在那里。 – WhozCraig 2013-04-11 14:47:30

+1

啊,是的,每天“我写信给存储单元,没有任何东西存在,为什么我会出现段错误”的问题。投票结束。 – Lundin 2013-04-11 14:59:13

在主:

int lines = 0, 
    words = 0, 
    sentences = 0, 
    characters = 0; 
... 
processFile(fileIn, &lines, &word,&sentences, &characters); 

在processFile

processFile(FILE* fileIn, int* lines, int* word, int* sentences, int* characters){ 
... 
} 

note :

fscanf(fileIn, "%d", &ch) < - 错

return *lines++; < - 不返回

的*线,*字等是其从未初始化为合适的存储器地址的所有指针。

如果你在main之外创建它们作为整数并删除所有的*前缀,它应该可以工作。

让这些整数不是指针通过在每一个去除*诠释

*lines = 0, 
*sentences = 0, 
*characters = 0, 
*words = 0; 

而且当你增加他们