简体   繁体   English

C - 计算文件中字母的出现 - 错误139:分段错误

[英]C - counting occurance of letters in a file - Error 139: Segmentation fault

I am writing a program, that counts the occurances of various letters in every line of a text file. 我正在编写一个程序,它计算文本文件每行中各种字母的出现次数。 I am doing this through a school website, which probably runs a debugger simmilar to Visual Basic. 我通过学校网站这样做,它可能运行与Visual Basic类似的调试器。 When I try to submit the code I get Error 139: Segmentation fault. 当我尝试提交代码时,我得到错误139:分段错误。 The program works in my own tests in CodeBlocks, but the site debugger encounters the error above. 该程序在我自己的CodeBlocks测试中工作,但站点调试器遇到上述错误。

The program waits for the user to input the name of the file to check. 程序等待用户输入要检查的文件的名称。 The contents of the file get saved into array "a". 文件的内容保存到数组“a”中。 Variable "Riadok" is a line counter and "pismena" is an array that stores letter occurance counts. 变量“Riadok”是行计数器,“pismena”是存储字母出现计数的数组。 The program checks each line and prints out a table showing how many times each letter was found in the line. 该程序检查每一行并打印出一个表格,显示在该行中找到每个字母的次数。

During submission the site checks for many different types of input and maybe there is something I didn't think of yet. 在提交过程中,网站会检查许多不同类型的输入,也许还有一些我还没有想到的东西。 Any advice please? 有什么建议吗? Also, I am a beginner coder so any advice about the code itself and improvement is welcome. 此外,我是一名初学者编码器,所以欢迎任何关于代码本身和改进的建议。

This is the code: 这是代码:

#include <stdio.h>
#include <ctype.h>
int main(){
 int riadok=1, pismena[26],i;
 char a[100],c='0';
 FILE *fr;

 for (i=0;i<=25;i++) pismena[i]=0;
 scanf("%s",a);
 fr= fopen(a, "r");
 printf("    A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z\n");
 while ((c=getc(fr))!=EOF){
  if(c!='\n') {
    c=toupper(c); 
    pismena[c-'A']++; 
  } 
  else if(c=='\n') {
    printf("%2d",riadok); 
    riadok++;
    for (i=0;i<=25;i++){
      printf(" %2d",pismena[i]);
      pismena[i]=0;
      c='0' ;
    }
    printf("\n");
   }
 } 
 printf("%2d",riadok); 
 riadok++;
 for (i=0;i<=25;i++){
   printf(" %2d",pismena[i]);
   pismena[i]=0;
 }
 printf("\n");
 fclose(fr);
 return 0;
}

This line can cause segmentation fault if c is anything other than a letter: 如果c不是字母,则该行可能导致分段错误:

pismena[c-'A']++; 

One way to fix it: 解决它的一种方法:

if (c >= 'A' && c <= 'Z') {
    pismena[c-'A']++; 
}

在对数组使用[c-'A']索引之前,应测试c是否在'A'和'Z'之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM