这个问题在网站上很难找到。我尝试过,但空手而归,所以如果之前有人问过类似的问题,我很抱歉。
本质上,我有一段带有两个 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 :
Sprite *sp;
sp = create_sprite(xpm, xi, yi, 0, 0);
这些值是通过终端给出的,我使用的是 xpm map ,除非我必须移动 Sprite ,否则它就可以工作。 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);
}
也就是说,您在释放
之后使用sp
时遇到了未定义的行为。这导致(在您的情况下)您读取垃圾值,从而导致 for 循环中出现意外的迭代量。
关于c - 分配的值不正确 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59504323/