-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;
}

here are my codes,when I run to getc().Mistake happend...

Program received signal SIGSEGV, Segmentation fault. _IO_getc (fp=0x0) at getc.c:37 37 getc.c: 没有那个文件或目录.

P.rong
  • 1
  • 1

1 Answers1

0

So to summarize the comments:

First of all, '\0' is end of string, not end-of-file. So instead of:

while(x!='\0'){

you should do this:

while (x != EOF) {

Secondly, you should verify that x-97 is in the index range of count before doing:

count[x-97]++;

Third, your function should not continue if p == NULL.

Ruud Helderman
  • 10,563
  • 1
  • 26
  • 45