final integer in loop not passing to function

C++ problem
Hi, I have 2 arrays of objects set up and they seem to be working fine. but I have a while loop set up in the main method. its setup is:

int MAX= 127, index=0;
while(index<=MAX && index>=0){

//cout<<"index1 = "<<index<<endl;
p[index].assignClassmember(index);
//cout<<"index2 = "<<index<<endl;
p[index].assignEnergy(index);
//cout<<"index3 = "<<index<<endl;

light[index].lAssignEnergy(index);
index++;
//cout<<"index6 = "<<index<<endl;
}

with the classes proton p[127] and phot light[127] set up above in the code and both of which containing perfectly working member functions. however, in this while loop it seems that when light[index].lAssignEnergy(index) runs it isn't recieving the final index integer (in the loop) correctly although for all others it works perfectly. the functions above it all recieve the correct value but lAssignEnergy messes up for the final, getting a completely random value of index, then immediately crashing the program. Help! The function lAssignEnergy is :

void lAssignEnergy(int j){
cout<<"light j = "<<j<<endl;
lTemp = 0.25 + 0.25*j;
cout<<"ltemp = "<<lTemp<<endl;
lEnergy = lTemp*(0.000001*0.00008671);
cout<<"lenergy = "<<lEnergy<<endl;
}

and the program writes out the "light j = " part but nothing else before it dies.
Last edited on
The problem ist this: while(index<=MAX && index>=0){ it must be while(index<MAX && index>=0){

An array is 0 based. So if you have p[127] 0 is the first value and 126 the last

One tip: When it comes to index a for loop is better
1
2
3
4
5
int MAX= 127, index=0;
while(index<=MAX && index>=0){
...
index++;
}
->
1
2
3
4
int MAX= 127
for(int index=0; index<MAX; index++){
...
}
thank you!! i was really scratching my head at this one
myx360 that was simple and good ....
Topic archived. No new replies allowed.