我试图让球在 ncurses 中左右弹跳。如果我打印普通结构并通过函数传递所述结构的指针,我可以让它正常工作。
当我运行以下代码时,它会打印我认为是结构元素的内存地址,而不是这些地址中包含的实际值。我不明白为什么第一段代码不起作用,但第二段代码起作用。我很确定我搞砸了指针,但我不知道在哪里。
糟糕的代码,
typedef struct Ball ball;
int width=80, height=20; //screen height/width in characters
struct Ball{
char shape;
int x;
int y;
int velX;
int velY;
};
ball* initBall(int X, int Y, int velx, int vely, char shape){
ball b;
ball *p = &b;
p->x = X;
p->y = Y;
p->velY = vely;
p->velX = velx;
p->shape = shape;
return p;
}
void moveBall(ball *b){
if(b->x +b->velX > width || b->x + b->velX < 0){
b->velX *= -1;
}
if(b->y +b->velY > height || b->y +b->velY< 0){
b->velY *= -1;
}
b->x += b->velX;
b->y += b->velY;
}
int main(){
ball *p = initBall(40,10,1,0, 'O');
int counter=0;
while(counter < 10){
printf("%d, %d\n", p->x, p->y);
moveBall(p);
counter++;
}
return 0;
}
好的代码,
typedef struct Ball ball;
int width=80, height=20; //screen height/width in characters
struct Ball{
char shape;
int x;
int y;
int velX;
int velY;
};
ball initBall(int X, int Y, int velx, int vely, char shape){
ball b;
ball *p = &b;
b.x = X;
b.y = Y;
b.velY = vely;
b.velX = velx;
b.shape = shape;
return b;
}
void moveBall(ball *b){
if(b->x +b->velX > width || b->x + b->velX < 0){
b->velX *= -1;
}
if(b->y +b->velY > height || b->y +b->velY< 0){
b->velY *= -1;
}
b->x += b->velX;
b->y += b->velY;
}
int main(){
ball b = initBall(40,10,1,0, 'O');
ball *p = &b;
int counter=0;
while(counter < 10){
printf("%d, %d\n", p->x, p->y);
moveBall(p);
counter++;
}
return 0;
}