无法在代码中找到错误的原因

标签 c

这是一个打印最小值及其在数组中的位置(由用户定义)的程序。

#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/

相关文章:

c - const char* 的地址是什么数据类型?

c++ - 如何在 OpenGL 中绘制顶点之间的边?

c - 在c中添加到字符串末尾的额外字符

C 预处理器定义每个字节都是 0xFF 的给定类型的值?

c - 绕过 CBMC 检测到的无符号加法溢出

python - ctypes 和结构数组

c++ - 如何让 MSVC 将未初始化的数据放入 .bss?

c - 平方反比定律方程

C:如何包含squash压缩库?

c++ - 在 MacOS 上编译 C/C++ 代码