分配的值不正确 - C



这个问题很难在网站上找到。我试过了,但空手而归,所以如果以前问过类似的问题,我很抱歉。

从本质上讲,我有一段带有两个 for 循环的代码。我相信它的目的对于我提出的问题来说是不必要的。无论如何,在我的代码中第二次调用此函数时(第一次工作正常(,分配给变量 x 和 y 的值不正确


void draw_sprite(Sprite *sp){
printf("outside ciclenx: %dny: %dn", (sp->x), (sp->y));
int y;
int x;
int p = 0;
for(y = sp->y; y < (sp->y + sp->height); y++){
for(x = sp->x; x < (sp->x + sp->width); x++){
printf("inside ciclenx: %dny: %dn", x, y);
vg_paint_pixel(x, y, sp->map[p]);
p++;
}
}
return;
}

程序打印出:

outside cicle
x: 34
y: 30
inside cicle
x: 0
y: 136663040

如您所见,在分配之前,x 和 y 的值分别为 34 和 30。但是在赋值它们之后,变量 x 和 y 变为 0 和 136663040。提前谢谢。

sp的定义:

typedef struct {
int x,y;             
int width, height;   
int xspeed, yspeed;  
char *map;           
} Sprite;

此函数的参数 (draw_sprite( 是按以下方式创建的精灵:

Sprite *sp;
sp = create_sprite(xpm, xi, yi, 0, 0);

这些值是通过终端给出的,我使用的是 xpm 地图,除非我必须移动精灵,否则该地图有效。值xi和yi都是30。以下是create_sprite函数:

Sprite * create_sprite(xpm_map_t xpm, int x, int y, int xspeed, int yspeed){
Sprite *sp = (Sprite *) malloc ( sizeof(Sprite));
if(sp == NULL){
return NULL;
}
xpm_image_t img;
sp->map = (char*)xpm_load(xpm, XPM_INDEXED, &img);
if(sp->map == NULL){
free(sp);
return NULL;
}
sp->width = img.width;
sp->height = img.height;
sp->x = x;
sp->y = y;
sp->xspeed = xspeed;
sp->yspeed = yspeed;
return sp;
}

此外,用于编译和生成所述错误:

int(video_test_move)(xpm_map_t xpm, uint16_t xi, uint16_t yi, uint16_t xf, uint16_t yf,
int16_t speed) {
Sprite *sp;
sp = create_sprite(xpm, xi, yi, 0, 0);
if (sp == NULL) {
printf("Error creating sprite.n");
return 1;
}
sp->xspeed = speed;
draw_sprite(sp);
if (speed > 0) {
while(sp->x != xf || sp->y != yf)){
destroy_sprite(sp);
sp->x += sp->xspeed;
sp->y += sp->yspeed;
draw_sprite(sp);
}      
}
return 0;
}

最后,为了使代码正常工作,还有destroy_sprite:

void destroy_sprite(Sprite *sp){
if(sp == NULL){
return;
} 
if(sp->map){
free(sp->map);
}
free(sp);
sp = NULL;
}

根据评论,特定问题听起来像是在

while(sp->x != xf || sp->y != yf)){
destroy_sprite(sp);
sp->x += sp->xspeed;
sp->y += sp->yspeed;
draw_sprite(sp);
}

也就是说,由于在free使用sp后,您遇到了未定义的行为。这导致(在您的情况下(读取垃圾值,从而导致 for 循环中的迭代量意外。

最新更新