使用字符串时出现分段错误

Segmentation error while working with strings

给定一个由字母和数字组成的字符串 num,找出给定字符串中每个数字 (0-9) 出现的频率。

'''

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include<ctype.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    char num[20];
    int i;
    int count[15]={0};
  
    scanf("%s",num);
    

    for(i=0;i<10;i++){
        printf("\n");     
        for(int j=0;j<strlen(num);j++){
            if(isdigit(num[j])){
               if(i == num[j]-'0'){
                count[i]+=1;
            }

            }
           
        }
        printf("\nCount %d:%d",i,count[i]);
    }  

    for(i=0;i<10;i++){
        printf("%d ",count[i]);
    } 
    return 0;
}

'''

输出:

计数0:5

计数1:9

计数2:5

计数3:12

计数4:8

计数5:11

计数6:15

计数7:4

计数8:4

退出,分段错误

为什么检查数字是否为 9 时不起作用?

查看您的输出时,您输入的字符串似乎比 19 个字符长得多。所以你的程序有未定义的行为。

这个

scanf("%s",num);

是你永远不应该做的事情。请记住将输入限制为缓冲区的大小。即:

char num[20];     // Size of buffer is 20

scanf("%19s",num);
        ^^
        At max allow 19 characters so that there is also room for the string termination

或者 - 也许更好 - 使用 fgets 而不是 scanffgets 的一个好处是它将缓冲区大小作为参数 - 因此您永远不会忘记指定它。

另请注意,您的外部 for 循环是不必要的。您可以使用单个循环直接更新数组。

// for(i=0;i<10;i++){  Delete this - it's not needed

    for(int j=0;j<strlen(num);j++)
    {
        if(isdigit(num[j]))
        {
            count[num[j]-'0']+=1;  // Update array
        }
    }

顺便说一句:计数器中只需要 10 个元素,即

int count[15]={0};   --->  int count[10]={0};