我想在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;
}
如果你編譯的時候啓用了警告,你會得到這樣的警告:'「警告:返回局部變量的地址」'......應該響鈴。 – 2013-11-01 09:07:14