-
Unknown Problem
I can't figure out why a program i'm working on keeps storing values in the wrong variables.
this is just the part of code that doesn't work, and I'm using Dev C++ to compile it. The problem occurs when it asks you to enter the value of 'position[2][3][2][1]' (on the screen in says "enter box 2,1 postion 2,3"), when you enter the value it somehow gets stored in the variable 'b' ('b' is the first variable displayed on each cout line, ie. it asks you to "enter box b,a position d,c" each line essentially).
I have attached the .cpp file if it helps, please just run the program (it's safe, u can see the code and compile it yourself) and when it asks you to "enter box 2,1 position 2,3" put in something like 5 (or a bigger number) and you'll see the problem on the next line straight away. In the code you can see this shouldn't happen.
The code is as follows:
Code:
#include <iostream>
using namespace std;
int main(){
int x, y, z, w, vars, known, a, b, c, d;
int position[3][3][3][3];
int posible[9];
for ( a=1; a <= 3; a++ ){
for ( b=1; b <= 3; b++ ){
for ( c=1; c <= 3; c++ ){
for ( d=1; d <= 3; d++ ){
cout<<"enter box "<< b <<","<< a <<" position "<< d <<","<< c <<"\n";
cin>> position[d][c][b][a];
}
}
}
}
// display start
for ( w=1; w <= 3; w++ ){
for ( y=1; y <= y; x++ ){
for ( z=1; z <= 3; z++ ){
for ( x=1; x <= 3; x++ ){
cout<< position[x][y][z][w] <<" ";
}
cout<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
cin.get();
cin.ignore();
// display end
}
*EDIT: the problem occurs in the code before where it displays (//display start), but occurs again in the displaying proccess. That is why I included it all, though you could compile only the code up to where it says "//display start" and still see the problem.
-
Code:
for ( x=1; x <= 3; x++ ){
cout<< position[x][y][z][w] <<" ";
x will go outside the valid range of 0..2 in this snippet of code. In C and C++, all arrays have a zero-based index, so an array with 3 elements has a valid index of 0, 1 and 2. 3 is outside of that. Since multidimensional arrays grow large pretty quickly, you are probably going way outside your actual memory, and things go wrong because of that.
The same applies to the input section.
--
Mats
-
oh, of course, silly me. I suppose the quick fix would be to make it an array of [4][4][4][4], though i should alter the code completely as to not waste memory.
Thanks heaps.
Also I did see the problem in the display's for y line. I just hadn't finished changing something when i copied the code.