2017-11-11 162 views
-1
  1. 当此代码运行时,它显示分段故障。但是,当地址(LessThan)countarray更改为地址< = countarray时,它可以工作。我只是想让它打印一个较少的数组,但它不允许我。使用阵列时C中的Segementation故障

    #include <stdio.h> 
    #include <stdlib.h> 
    
    int main() 
    { 
    int n,check,divisor,countarray,address; 
    int pn[100]; 
    
    for (n=2;n<100;n++){ 
        for (divisor=2;divisor<n;divisor++){ 
         if ((n/divisor)*divisor==n) //if (n is not a prime number) 
          check++; 
        } 
        if (check==0){     //if its a prime number, 
         pn[countarray]=n; 
         countarray++; 
        } 
    
        check=0; 
    
    } 
    
    for (address=0;address<countarray;address++) 
        printf("address for %d is %d and ",pn[address],address); 
    
    
    return 0; 
    } 
    
+1

'countarray'未被初始化。也检查。 – alk

+0

您可能想要阅读以下内容:[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – alk

+2

在初始化之前使用许多变量。未初始化的本地变量将具有*不确定*值,这看起来是随机的。例如,如果'countarray'的值超出了'pn'数组的范围,该怎么办?然后'pn [countarray] = n'会导致[* undefined behavior *](https://en.wikipedia.org/wiki/Undefined_behavior)。 –

回答

3

没有与条件address<countarray没有问题,你应该初始化检查 & countarray变量。

int n,check=0,divisor,countarray=0,address;