这是我在 main 和函数“checkCollisionOrFood()”中初始化数组“turn[20]”的代码,四个值 turn[0],turn[1],turn[2],turn[3]在主函数中初始化为零,其余部分在“checkCollisionOrFood()”中初始化。这是故障开始的地方。当我在“checkCollisionOrFood()”中初始化 turn[4]=0 然后在任何地方访问它时,它仍然为 0任何功能,但是!当我初始化下一个转弯[]即转弯[5]时,转弯[4]的值被耗尽。即转弯[4]有垃圾值。转弯[20]是全局变量,它的索引“头”也是全局的。我我被这个问题困住了,请帮我摆脱它。这是我的完整代码
#include <mega8.h>
#include <delay.h>
#include <stdlib.h>
unsigned short address[]= {0b00001111,0b00000000,0b00000000,0b00000000,
0b00000000,0b00000000,0b00000000,0b00000000};
unsigned short turn[20];//it is declared as global variable.
unsigned short head=3;
unsigned short colHead=0;
unsigned short rowHead =3;
unsigned short rowTail=0;
unsigned short colTail=0;
unsigned short size=4;
unsigned short foodx;
unsigned short foody;
...
unsigned short checkCollisionOrFood()
{
head=(head+1)%20;
if(turn[head-1]==0){
turn[head]=0;
/这是turn []被初始化的地方,如果我在这里访问turn [head],即在iniliazition之后,那么它会给出正确的值,但是如果我访问它的先前值意味着turn [head-1],那么它会给出垃圾值/
PORTB=255;PORTB&=~(1<<turn[4]);PORTD.7=0;delay_ms(200);PORTD.7=1;
/通过这个语句,我在turn[4]初始化之后检查了turn[4]的值,它给出了正确的答案,然后在turn[5]初始化之后访问turn[4]给出了垃圾。/
rowHead=(rowHead+1)%8;
if(!(address[colHead]&(1<<rowHead)))return 1;
else if((address[colHead]&(1<<rowHead))&&
(!((colHead==foody)&&(rowHead==foodx))))gameOver();
else return 0;
}
if(turn[head-1]==1){
turn[head]=1;
colHead=(colHead+1)%8;
if(!(address[colHead]&(1<<rowHead)))return 1;
else if((address[colHead]&(1<<rowHead))&&
(!((colHead==foody)&&(rowHead==foodx))))gameOver();
else return 0;
}
}
void main(void)
{
turn[0]=0;turn[1]=0;turn[2]=0;turn[3]=0;
/无论在哪里访问它们,turn[] 的这些值都不会改变。/
while (1)
{
if(checkCollisionOrFood())
{
PORTB=(address[colHead] |=1<<rowHead);
turnOffTail();
blink();
}
else
{
PORTB=address[colHead];
createFood();
blink();
}
}
}
请建议我摆脱它。