我遇到了分割错误C的问题
我试图打开一个文件,看看文件中有多少行、单词、字符和句子。一切都可以编译,但当程序运行时,它会打印指令,然后出现分段错误。我知道文件可以打开,所以我猜我在processFile中做错了什么。帮帮忙太好了 另外,include lib09.h是main之后的三个函数我遇到了分割错误C的问题,c,segmentation-fault,C,Segmentation Fault,我试图打开一个文件,看看文件中有多少行、单词、字符和句子。一切都可以编译,但当程序运行时,它会打印指令,然后出现分段错误。我知道文件可以打开,所以我猜我在processFile中做错了什么。帮帮忙太好了 另外,include lib09.h是main之后的三个函数 #include <stdio.h> #include <stdlib.h> #include "lib09.h" int main(void) { FILE *fileIn; int *line
#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;
}
*行、*字等都是从未初始化为正确内存地址的指针
如果您在main之外创建它们作为int,并删除所有*前缀,它应该可以工作。使这些int不是指向int的指针
*lines = 0,
*sentences = 0,
*characters = 0,
*words = 0;
通过删除每一个中的*以及在main中增加它们时:
int lines = 0,
words = 0,
sentences = 0,
characters = 0;
...
processFile(fileIn, &lines, &word,&sentences, &characters);
在进程文件中
processFile(FILE* fileIn, int* lines, int* word, int* sentences, int* characters){
...
}
注:
fscanffileIn,%d,&ch您正在向processFile函数中的四个不同的空指针写入数据。可以肯定的是,您打算将这些参数作为按地址输入参数传递给函数,并将&var参数传递回调用方。当然,函数本身无论如何都是错误的,因为它在处理任何字符时都会错误地返回。我认为,给定函数的名称,这些返回语句中的任何一个都不应该存在。啊,是的,我每天都在向不存在任何内容的存储单元写入内容,为什么我会遇到这样的问题。投票结束。