简体   繁体   English

一旦我运行我的代码,就会出现分段错误。 arrays 似乎有问题

[英]Segmentation fault as soon as i run my code. Seems like problem with arrays

I wrote code which prompts the user for a number, then tell which digits are of that number are repeated.我编写了提示用户输入数字的代码,然后告诉该数字的哪些数字是重复的。
While there is no problem with compilation, it shows segmentation fault(core dumped) when i run it.虽然编译没有问题,但当我运行它时它显示分段错误(核心转储)。

Code:代码:

 #include <stdio.h>

 int main(void)
 {
    int n=0;
    int digit[n];
    int t;
    
    for (int num = 0;num<10;num++)
    {
        digit[num] = 0;
    }
    
    scanf("%d",&t);
    int y=t;
    int c = 0;
    
    do
    {
        c++;
        y = y/10;
    }while(y>0);
    
    int ko;
    
    for (int no=0;no<c;no++)
    {
        ko = t%10;
        digit[ko]++;
        t=t/10;
    }
    
    int count = 0;
    
    for (int co = 0;co<10;co++)
    {
        if (count>0)
            printf(" ");
    
        if (digit[co]>1)
        {
            printf("%d",co);
            count ++;
        }
    }
 }

The problem lies here:问题出在这里:

int n=0;
int digit[n];

This makes digit an array of 0 int s, which is not what you need.这使digit成为 0 int的数组,这不是您所需要的。 Looking at看着

for (int num = 0;num<10;num++)
{
    digit[num] = 0;
}

This makes me think that you need to iterate over 10 array elements.这让我认为您需要迭代 10 个以上的数组元素。 So make it,就这样吧,

int digit[10];

Or even better define a macro and use it elsewhere.或者甚至更好地定义一个宏并在其他地方使用它。

#define LIMIT_ARRAY_ELEMENTS (10)

and then接着

int digit[LIMIT_ARRAY_ELEMENTS];

and

for (int num = 0; num < LIMIT_ARRAY_ELEMENTS; num++)

The segmentation fault you see is because you have not allocated enough memory for what you are trying to do.您看到的分段错误是因为您没有为您尝试执行的操作分配足够的 memory。

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

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