程序崩溃序列排序程序
Program crash sequence sorting program
在修复完错误后,我运行了程序,它崩溃了。尝试修复该程序一段时间,但无法修复。该程序是关于序列和排序的。编译器是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--;
}
}
}
您正试图访问您不拥有的内存。
int N;
int a[ N ];
您正在声明N,然后用它定义数组,但此时它还没有初始化。然后,当你试图写入内存中的位置时,它会产生错误。
您正在定义一个具有可变N
大小的数组。使用指示的:
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
}
相关文章:
- 使用C++程序合并排序没有得到正确的输出
- 显示错误输出的简单数组排序程序
- 在气泡排序程序中未声明错误功能
- 在自定义程序中使用本机 Windows 自然顺序排序
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 我的排序算法程序中的堆错误
- 无法在基于 DFS 的任务排序程序中填充"stack"
- 排序程序的意外错误代码
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 无法在 Visual Studio 程序中运行合并排序
- OOP 气泡排序C++程序
- 编写程序,导入三个浮点数a,b和c.按升序排序
- 尝试对对象数组进行排序时程序终止
- 家庭作业的排序链表程序中的分段错误
- 试图理解合并排序程序
- 排序程序的错误(检测到堆损坏)
- 字母选择排序程序的问题
- 这个合并排序程序有什么问题
- 我正在尝试为 Kruskal 算法实现一个C++程序,该程序需要我按权重对图形进行排序。如何按权重对结构进行排序
- 程序排序三个整数值