-1
#include<stdio.h>
int main(){
    int count[26];
    for(int i=0;i<26;i++){
        count[i]=0;
    }
    printf("xx1");
    FILE *p;
    printf("xx");
    p=fopen("test.txt","r");
    if(p==NULL)
        printf("error");
    int x=fgetc(p);
    while(x!='\0'){
        count[x-97]++;
        x=getc(p);
        }
    for(int i=0;i<26;i++){
        printf("%c:%d\t",i+97,count[i]);
    }
    fclose(p);
    return 0;
}

这是我的代码,当我跑到 getc() 时。错误发生了......

程序收到信号 SIGSEGV,分段错误。_IO_getc (fp=0x0) at getc.c:37 37 getc.c: 没有那个文件或目录。

4

1 回答 1

0

所以总结一下评论:

首先,'\0'是字符串结尾,而不是文件结尾。所以而不是:

while(x!='\0'){

你应该做这个:

while (x != EOF) {

其次,您应该在执行以下操作之前验证它x-97是否在索引范围内count

count[x-97]++;

第三,如果p == NULL.

于 2020-05-11T08:57:54.407 回答