分配了不正确的值-C

问题描述 投票:0回答:1

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

本质上,我有一段代码,其中包含两个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;
}
c for-loop int assign
1个回答
0
投票

根据评论,听起来像是具体问题所在

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

即,由于在sp添加后使用free而遇到不确定的行为。这(在您的情况下)导致您读取垃圾值,从而在for循环中导致意外数量的迭代。

© www.soinside.com 2019 - 2024. All rights reserved.