中止陷阱:C 中的6个错误

Abort trap :6 Error in C++

本文关键字:中的 6个 错误 陷阱      更新时间:2023-10-16

我是编程的新手,所以如果问题听起来很琐碎,请原谅我。您的任何建议将对我的学习有很大的帮助。我正在编写大小10的阵列上的选择_sorting程序信息:排序的数组如下: 中止陷阱:6

我的问题是在程序中在哪里寻找问题,该问题发生了什么原因?

是什么原因?

作为参考,我正在附上我的代码。

# include <iostream>
void fill_array(int sample_array[10], int size);
void sort(int sample_array[10], int size);
void swap(int &a1, int &a2);
int index_of_smallest(int array[10], int start_index, int size);
int main()
{
    using namespace std;
    int array[10];
    fill_array(array, 10);
    sort(array, 10);
    cout << " The sorted array as follows : n";
    for (int i = 0; i < 10; i++)
    {
        cout << array[i] << " ";
    }
    return 0;
}
void fill_array(int sample_array[10], int size)
{
    using namespace std;
    for (int index = 0; index< 10; index++)
    {
        cin >> sample_array[index];
    }
}
void swap(int &a1, int &a2)
{
    int temp;
    temp = a1;
    a1 = a2;
    a2 = temp;
}
int index_of_smallest(int array[10], int start_index, int size)
{
    int min = array[start_index];
    int min_index = start_index;
    for (int i = start_index + 1; i< size - 1; i++)
    {
        if (array[i]< min)
        {
            min = array[i];
            min_index = i;
        }
    }
    return min_index;
}
void sort(int sample_array[10], int size)
{
    int next_min_index;
    int j;
    for (j = 0; j < size; j++)
    {
        next_min_index = index_of_smallest(sample_array, j, 10);
    }
    swap(sample_array[j], sample_array[next_min_index]);
}

我决定破译最有可能故障的一个函数。我在这里重新格式化它是可读的:

void sort( int sample_array[10], int size )
{
    int next_min_index;
    int j;
    for( j = 0; j < size; j++ )
    {
        next_min_index = index_of_smallest( sample_array, j, 10 );
    }
    swap( sample_array[j], sample_array[next_min_index] );
}

现在,希望您能看到问题。

互换不会发生在循环内。您将j的定义移出了循环范围(大概是为了修复您不了解的编译错误,这将使您指出问题)。

j == 10时,互换正在发生。那在您的阵列界限和程序包的范围之外。如果将功能更改为此:

,则应解决错误
void sort( int sample_array[10], int size )
{
    for( int j = 0; j < size; j++ )
    {
        int next_min_index = index_of_smallest( sample_array, j, 10 );
        swap( sample_array[j], sample_array[next_min_index] );
    }
}

这可能不是唯一的问题,但是我不会破译您的其余代码。希望此修复程序加上一些强烈的鼓励使用人类可读的代码布局将帮助您沿途。