-
Ahhh Errorrrrs!!!
Could anyone help me out?
I'm doing a problem that requires a 2 dimensional array, and everything is working fine and storing. However, at the end of the program I get 3 error messages saying the program is crashed even though it executed properly. I'm using Borland c++ 5, here's the code if it'll help out
#include <stdio.h>
#include <iostream.h>
#include <time.h>
#include <stdlib.h>
void main(){
int matrix[4][5];
int rr,cc;
int max=500;
int min=-500;
randomize();
for (rr=1;rr<=4;rr++){
for (cc=1;cc<=5;cc++){
matrix[rr][cc] = (rand() % (max + 1 - min)) + min;
cout <<matrix[rr][cc]<<" ";
}
cout <<"\n";
}
//return(0);
}
-
You're violating the array bounds.
int matrix[4][5] has four rows (0 through 3) and five columns (0 through 4). All indexes start at zero -- you're starting at one.
Change it to:
Code:
for (rr=0;rr<4;rr++){
for (cc=0;cc<5;cc++){
-
You've made a very common error for beginners, that I made countless times when learning C:
if you declare an array as
type array[5];
the value array[5] is OUTSIDE the range of the array. The array goes from 0 - 4, NOT 0 - 5 or 1 - 5.
So, use < instead of <= in your for loop, and start with 0 instead of 1.
Edit: I see I was beaten to the response by a few seconds. I'll leave this up anyway.