【问题标题】:C - Getting a segmentation fault(core dumped) error in this simple programC - 在这个简单的程序中出现分段错误(核心转储)错误
【发布时间】:2016-12-17 23:39:49
【问题描述】:

这是一个简单的程序,它找到 10 数组的最小和最大元素。我不确定为什么会出现分段错误(核心转储)错误。

#include <stdio.h>

int main(void) {
    int i, j, min, array[10], max, n;

    //This loop get user input for the elements of the array
    for(i = 0; i < 10; i++) {                   
        printf("Enter element number %d:", i);
        scanf("%d", &n);
        array[i] = n;
    }

    min = array[0];
    max = array[0];

    //This loop finds the smallest element of the array
    for(j = 0; j < 10; j++) {
        if(min > array[j]) {
            min = array[j];
        }
    }

    //This loop finds the largest element of the array
    for(j = 9; j >= 0; j++) {
        if(max < array[j]) {
            max = array[j];
        }
    }

    printf("smallest value is: %d", min);
    printf("largest value is: %d", max);

    return 0;
}

【问题讨论】:

  • 答案告诉你是你的错误,所以我会暗示一些别的东西:试着找到一种方法,你只使用线性时间来找到最小值和最大值,而不是二次时间。跨度>
  • @MeikVtune 这里没有二次元...你的意思是一次遍历而不是两次遍历?
  • @Quentin 是的 :)

标签: c segmentation-fault


【解决方案1】:
for(j = 9; j >= 0; j++)

应该是

for(j = 9; j >= 0; j--)

如果你想从最后一个迭代到第一个。您在第二次迭代中访问array[10],这是超出范围的。

也没有理由从最后一个迭代到第一个,所以

for(j = 0; j < 10; j++)

也可以。

您可以在单个 for 循环中完成整个工作(从标准输入读取,查看它是否大于最大值/小于最小值),因此您不需要数组。

【讨论】:

    【解决方案2】:
    for (j = 9; j >= 0; j++)
    

    这里你从 9 开始做 j++!

    这样做:

    for (j = 9; j >= 0; j--)
    

    顺便说一句,你可以这样做

    scanf("%d", array + i);
    

    【讨论】:

      【解决方案3】:

      下面的循环试图指向超出分配内存空间的位置。

      for(j = 9; j >= 0; j++) 
      

      改为尝试写作:

      for(j=9; j >= 0; j--) 
      

      如果您愿意,可以按照@mch 的建议进行递增循环。 另外,作为建议,请在此处跳过使用变量 j。您可以改用i。不会有任何问题,因为您在循环中将0 分配给它。您将节省 4 个宝贵的字节。

      【讨论】:

        猜你喜欢
        • 2019-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多