Hi,
Just started using NXC.
Want to make a connect 4 Robot Game (with NXT display).
At the moment I can't even get an int value out of the array and test it.
Please explain, I get "File error!".
the line: "ArrayIndex(myVal,col1,i);" - is the issue as it seems to cause the "if" to fail.
//This program should output the position in array col1
// where the 1st "0" is encountered. should display "2"
//
int myVal = 0;
int currentCol = 1;
int colEmptyLocation = 0;
int col1[6], col2[6], col3[6],col4[6], col5[6], col6[6], col7[6], col8[6];
//
//
task main()
{
//test values
col1[0]=2;
col1[1]=2;
col2[0]=1;
col2[1]=1;
col2[2]=2;
col3[0]=2;
//
for(int i=0; i <= ArrayLen(col1); i++) {
//either line below does not work! causes "File error!"
//myVal= col1[i];
ArrayIndex(myVal,col1,i);
//
if (myVal==0){
colEmptyLocation = i;
NumOut(10,LCD_LINE2,colEmptyLocation);
i = 100;
}
}
Wait(10000);
}
Welcome!
Well, the problem is that in your for-loop:
for(int i=0; i <= ArrayLen(col1); i++)
You put i <= ArrayLen(col1);
It is supposed to be i < ArrayLen(col1)
It is supposed to be less than, not less than or equal to.
Using <=, the program tries to get a value in the array that is out of bounds, which will create a file error.
Thanks for that but...there's no problem with the loop.
I just re-started everything and re-ran the code and it works.
So what I think happened is that the program got confused as I forgot to declare the "myVal" variable initially and from that point it just assumed "myVal" was a local variable, and confused myself and it. Is that possible?
Thanks anyway, I'm sure to have more questions coming your way.
I am sure that nxtboyiii was correct to point out that you cannot access an array of size N using an index equal to N. If you try that you will get a File Error abort. Arrays in C are indexed from 0 to N-1 where N is the array length or size, i.e., if the array has 10 elements in it then you would index it from 0 to 9 - not from 0 to 10, which would be 11 elements.
if you forgot to declare myVal initially then the program could not have compiled using the NBC/NXC compiler. Programs never get confused. Programmers sometimes do but Programs never do. They always know exactly what you told them to do and they try to do it even when it is impossible.
For normal code I would not recommend using ArrayIndex but instead use standard C array syntax, like what you have commented out immediately above ArrayIndex. And get rid of the <= and use < instead in your for loop declaration.
Hi,
Yes you are correct on the loop, but it didn't error because I used i = 100; There was some other problem that fixed itself upon restarting everything.
Actually is using i = 100 the correct way to escape the loop?
Thanks
Michael.