-1

完成修复错误后,我运行程序并崩溃。尝试修复程序一段时间但不能。程序是关于序列和排序的。编译器是 devcpp。似乎不是堆栈溢出。:)

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip> 
#include <conio.h>

using namespace std;

void selectionSort(int *, int);

int main()
{
    int N;
    int a[ N ];

    cout << "\n Enter the length of sequence:";
    cin >> N;

    for (int i = 0; i < N && i < 5; ++i)
    {
        a[ N ] = rand() % 1000000 + 0;
        srand(time(0));
        cout << "Random sequence";
        for (int i = 0; i < N; i++)
            cout << setw(4) << a[i];
        cout << endl;
    }

    cout << "Sorted sequence";
    selectionSort(a, N);
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;
    getch();
}

void selectionSort(int *array, int N)
{
    int temp, i, j;
    for (i = 0; i < N - 1; i++)
    {
        j = i;
        while (j > 0 && array [j - 1] > array [j])
        {
            temp = array [j];
            array[j] = array [j - 1];
            j--;
        }
    }
}
4

2 回答 2

2

您正在定义一个可变N大小的数组。使用这个 insted:

int *a = new int[N];
// ...
delete [] a;

第二个问题是a[N] = ...访问不存在的元素。

此外,最好放在srand(time(0));代码的开头,而不是循环。

int main()
{
    srand(time(0));

    int N;
    cout << "\n Enter the length of sequence:";
    cin >> N;

    int *a = new int[N]; // If you compiler support you can: int a[N];

    for (int i = 0; i < N; ++i)
    {
        a[ i ] = rand() % 1000 + 0;
    }

    cout << "Random sequence";
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;


    cout << "Sorted sequence";
    selectionSort(a, N);
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;
    getch();

    delete [] a; // If you use pointer version
}
于 2013-02-24T21:42:38.800 回答
2

您正在尝试访问不属于您的内存。

 int N;
 int a[ N ];

您正在声明 N 然后用它定义您的数组,但在那个时间点它还没有被初始化。然后,当您尝试写入内存中的位置时,它会出现故障。

于 2013-02-24T21:43:10.023 回答