这是一个打印最小值及其在数组中的位置(由用户定义)的程序。
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[n];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<=n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
但是运行它时,它显示以下错误:
Segmentation fault (core dumped)
可能的原因是什么?
最佳答案
第一个错误,如其中一条注释中所述,是在知道 n 是多少之前就声明了大小为 n 的数组。
第二个错误是主函数中的 for 循环从 0 到 n,即数组的索引超出范围。
试试这个:
int main() {
int n = 0, j = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for (j = 0; j < n; j++) {
printf("a[%d] = ", j + 1);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
如果这解决了您的问题,请标记它。
关于无法在代码中找到错误的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55190694/