我一直在查看我的代码一段时间了,我无法弄清楚为什么这个错误会不断出现。它可能非常简单,但我无法理解......
“program.exe中0x00FB59E6处的未处理异常:0xC0000005:访问冲突写入位置0x00000009。”
这是在第三次重复程序时发生的
的main.cpp
#include <iostream>
#include <string>
#include "functions.h"
using namespace std;
int main(){
RandomArray();
MinMaxArray();
SortedArrays();
cout << "\n\nWould you like to re-run? (Y/N): ";
cin >> y;
if (y == "Y" || y == "y"){
system("CLS");
main();
}else{
system("PAUSE");
}
return 0;
}
functions.h
#include <iostream>
#include <time.h>
using namespace std;
int array[50], used[50], sortedArray[50];
int buildSort = 1, genNum, mx = 0, mn = 100;
bool x;
string y;
int RandomArray(){
srand(time(0));
for(int a = 0; a < 50; a++){ //array generator
do{
genNum = (1+rand()%100); //generate a # between 1-100
x = false;
for(int b = 0; b < 50; b++){
if(genNum == used[b]){ //if the number is already used...
x = true;
}
}
}while(x == true);
used[a] = genNum;
array[a] = genNum;
}
cout << "Random array: " << endl;
for(int c = 0; c < 50; c++){
cout << array[c] << " "; //display the random array
}
cout << endl << endl;
return 0;
}
int MinMaxArray(){
for(int d = 0; d < 50; d++){ //for each number in the array
if(array[d] > mx){ //check to see if each number is greater than mx
mx = array[d]; //the max equals that number it picked out
}
if(array[d] < mn){ //check to see if theres a number is less than mn
mn = array[d]; //the minimum equals that number it picked out
}
}
cout << "Maximum: " << mx << endl; //display the max
cout << "Minimum: " << mn << endl << endl; //display the min
return 0;
}
int SortedArrays(){
sortedArray[0] = mn;
for(int e = mn + 1; e <= mx; e++){ //goes through 1-100 and adds each number to another array in order
for(int f = 0; f < 50; f++){
if(array[f] == e){
sortedArray[buildSort] = array[f];
buildSort++;
}
}
}
cout << "Sorted array: " << endl;
for(int g = 0; g < 50; g++){
cout << sortedArray[g] << " "; //display sorted from lowest to highest
}
cout << endl << endl;
cout << "Reverse sorted: " << endl;
for(int h = 49; h >= 0; h--){
cout << sortedArray[h] << " "; //display sorted from highest to lowest
}
return 0;
}
答案 0 :(得分:1)
您正在使用第一次初始化的一些变量:buildSort,mx和mn; 在主要开头添加类似
的内容int main()
{
buildSort = 1;
mx = 0;
mn = 100;
RandomArray();
MinMaxArray();
SortedArrays();
}
再试一次。 您的buildSort会让您耗尽阵列。
只是一个建议:尝试更好地编写代码!几乎不可读!!!
答案 1 :(得分:0)
system
功能来处理CLS
和PAUSE
等基本功能,您可以使用clrscr()
或getch()
(或相应的功能) main
- 这不是为了这个目的。虽然没有编译器会抱怨,但这是不好的方法。