这是我在main和函数"checkCollisionOrFood()"中初始化数组"turn[20]"的代码,四个值turn[0]、turn[1]、turn[2]、turn[3]在main函数中初始化为零,其余在"checkCollision OrFood"中初始化。这就是故障开始的地方。当我在"check科里sionOrFoo()"中将turn[4]初始化为0,然后在任何地方访问它时,它在任何函数中都保持为0,但是!当我初始化下一个turn[],即turn[5]时,turn[4]的值被耗尽。即turn[4]有垃圾值。turn[20]是全局变量,其索引"head"也是全局的。我被这个问题卡住了,请帮我摆脱它。这是我的完整代码
#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],即在初始化之后,它会给出正确的值,但如果我访问它的前一个值意味着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();
}
}
}
Plz建议我离开它。
如果您在head
中观察到垃圾,这可能很容易是由于访问address
越界,因为它位于内存中turn
之前
检查address
的索引,以确保您的写入不会超出其边界,并在下一个变量(即turn
)中覆盖数据。
unsigned short checkCollisionOrFood()
{
head=(head+1)%20;
if(turn[head-1]==0){
turn[head]=0;
当"头"达到"20"时,你可能会遇到问题。"head"的值随后回滚到0,这将导致您测试"turn[-1]"的值。