[英]C - Getting a segmentation fault(core dumped) error in this simple program
这是一个简单的程序,可以找到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;
}
for(j = 9; j >= 0; j++)
应该
for(j = 9; j >= 0; j--)
如果要从最后一个迭代到第一个。 您在第二次迭代中访问array[10]
,这是超出范围的。
同样也没有理由从最后一个迭代到第一个
for(j = 0; j < 10; j++)
也可以。
您可以在单个for循环中完成整个工作(从stdin读取,查看它是否大于最大值/小于最小值),因此不需要数组。
for (j = 9; j >= 0; j++)
在这里,您从9开始并开始使用j ++!
做这个:
for (j = 9; j >= 0; j--)
顺便你可以做到这一点
scanf("%d", array + i);
下面的循环试图指向超出分配的内存空间的位置。
for(j = 9; j >= 0; j++)
而是尝试编写:
for(j=9; j >= 0; j--)
如果您愿意,可以按照@mch的建议进行递增循环。 另外,建议您在此跳过使用变量j
。 您可以改用i
。 不会有任何问题,因为您正在循环中为其分配0
。 您将节省4个宝贵的字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.