C ++中的访问冲突错误
问题描述:
这是一个程序,该程序生成一个随机的2维数组,并按对角线元素升序排列.我收到"Acess Violation"错误,无法理解why.here,这是我到目前为止的内容.这个家伙有什么线索吗?
Laba6.exe中0x011bbfed的未处理异常:0xC0000005:访问冲突读取位置0x00000061.
This is a program that generate a random 2 dimensinal array and sots its diagonal elements in ascending order. I get an "Acess Violation" error and cant understand why.here it is what i have so far. any clue on this one guys?
Unhandled exception at 0x011bbfed in Laba6.exe: 0xC0000005: Access violation reading location 0x00000061.
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<time.h>
#define WIDTH 4
#define HEIGHT 4
using namespace std;
int jimmy [HEIGHT][WIDTH];
int n,m;
void bubblesort (int jimmy[HEIGHT][WIDTH], int length);
int main ()
{
srand ( static_cast<unsigned int>(time(NULL)) ); //initialize time
for (n=0;n<HEIGHT;n++) //set HEIGHT
for (m=0;m<WIDTH;m++) //set WIDTH
{
jimmy[n][m]=(rand( )%(99)); //Initilaize random Matrix
}
//Print Out Random Matrix
cout <<"|"<< jimmy[0][0]<<","<< jimmy[0][1]<<","<< jimmy[0][2]<<","<< jimmy[0][3]<<"|"<<endl;
cout <<"|"<< jimmy[1][0]<<","<< jimmy[1][1]<<","<< jimmy[1][2]<<","<< jimmy[1][3]<<"|"<<endl;
cout <<"|"<< jimmy[2][0]<<","<< jimmy[2][1]<<","<< jimmy[2][2]<<","<< jimmy[2][3]<<"|"<<endl;
cout <<"|"<< jimmy[3][0]<<","<< jimmy[3][1]<<","<< jimmy[3][2]<<","<< jimmy[3][3]<<"|"<<endl;
bubblesort(jimmy, 10);
//Sorted Matrix
cout <<"|"<< jimmy[0][0]<<" , "<< jimmy[0][1]<<" , "<< jimmy[0][2]<<" , "<< jimmy[0][3]<<"|"<<endl;
cout <<"|"<< jimmy[1][0]<<" , "<< jimmy[1][1]<<" , "<< jimmy[1][2]<<" , "<< jimmy[1][3]<<"|"<<endl;
cout <<"|"<< jimmy[2][0]<<" , "<< jimmy[2][1]<<" , "<< jimmy[2][2]<<" , "<< jimmy[2][3]<<"|"<<endl;
cout <<"|"<< jimmy[3][0]<<" , "<< jimmy[3][1]<<" , "<< jimmy[3][2]<<" , "<< jimmy[3][3]<<"|"<<endl;
system ("pause");
return 0;
}
//bubblesort rearranging algorithm
void bubblesort (int jimmy[HEIGHT][WIDTH], int length)
{
int index;
int iteration;
int temp;
for(iteration = 1; iteration < length; iteration++)
{
for(index = 0; index < length - iteration;index++)
if(jimmy[index][index] > jimmy[index + 1][index + 1])
{
temp = jimmy[index][index];
jimmy[index][index] = jimmy[index + 1][index + 1];
jimmy[index + 1][index + 1] = temp;
}
}
}
答
在Bubblesort()中,您将传入参数"length"用作数组索引的范围. >
数组定义为4 x 4,但是您传递10作为参数,因此Bubblesort()尝试像访问10 x 10一样对其进行访问.
BOOM!
Inside Bubblesort(), you use the incoming parameter ''length'' as the range on the indices into the array.
The array is defined to be 4 x 4 yet you pass 10 as the argument so Bubblesort() tries to access it as if it was 10 x 10.
BOOM!