这个问题很难在网站上找到。我尝试过,但是空手而归,所以很抱歉以前是否曾提出过类似的问题。
从本质上讲,我有一段代码,其中包含两个for循环。我认为它的目的对于我要问的问题是不必要的。无论如何,第二次在我的代码中调用此函数(第一次运行良好)分配给变量x和y的值不正确。
void draw_sprite(Sprite *sp){
printf("outside cicle\nx: %d\ny: %d\n", (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 cicle\nx: %d\ny: %d\n", 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;
}
答案 0 :(得分:1)
根据评论,特定问题听起来像是
while(sp->x != xf || sp->y != yf)){
destroy_sprite(sp);
sp->x += sp->xspeed;
sp->y += sp->yspeed;
draw_sprite(sp);
}
也就是说,您在sp
设置后使用free
会遇到未定义的行为。这(在您的情况下)导致您读取垃圾值,从而在for循环中导致意外数量的迭代。