【问题标题】:Segmentation fault in C when using arrays使用数组时 C 中的分段错误
【发布时间】:2017-11-11 09:02:39
【问题描述】:
  1. 运行此代码时,会显示分段错误。但是当 address(LessThan)countarray 更改为 address

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

【问题讨论】:

  • countarray 未初始化。 check 也是。
  • 您可能想阅读以下内容:How to debug small programs
  • 您在初始化之前使用了许多变量。未初始化的局部变量将具有一个看起来随机的 indeterminate 值。例如,如果countarray 有一个超出pn 数组范围的值怎么办?然后pn[countarray]=n 将导致undefined behavior。

标签: c arrays segmentation-fault


【解决方案1】:

条件address&lt;countarray没有问题,你应该初始化check & countarray变量。

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

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多