开发者

passing pointer to change its value but stay still

开发者 https://www.devze.com 2023-03-30 23:28 出处:网络
passing pointer to change its value but stay still I am working on C++ with allegro library. there is draw_tiles function.

passing pointer to change its value but stay still

I am working on C++ with allegro library.

there is draw_tiles function.

void draw_tiles(def_small_world * s_world,BITMAP * dest){
    BITMAP *TileMap=NULL; 

    loadTilemap(s_world->tilemap,TileMap); 
    for(int y = 0;y<SIGHTY*2+1;y++)
    {
        for(int x = 0;x<SIGHTX*2+1;x++)
        {
            pasteTile(s_world->tile[y][x].kind,TileMap,dest,x,y);
        }
    }

}

and loadTilemap function.

void loadTilemap(int i,BITMAP * tileLayer){
    char c[128];
    sprintf(c,TILEPATHFORMAT,i);
开发者_运维问答    tileLayer= load_bitmap(c,NULL);
}

I expect

following code change TileMap to points somewhere

loadTilemap(s_world->tilemap,TileMap); 

but after loadTilemap, the TileMap variable stay still.

the following code works very well

char c[128];
sprintf(c,TILEPATHFORMAT,i);
tileLayer= load_bitmap(c,NULL);

tileLayer points 0x003f93f8

How to fix my code to TileMap points return value of load_bitmap?


You are passing the pointer by value, so a copy of the pointer is created. Inside loadTilemap, you are assigning a new value to the copy of the pointer - but that doesn't affect the original pointer.

Try passing the pointer by reference by changing the loadTilemap function signature to this:

void loadTilemap(int i,BITMAP *& tileLayer);


You need to pass a pointer to pointer to achieve that:

void loadTilemap(int i,BITMAP ** tileLayer){
   char c[128];
   sprintf(c,TILEPATHFORMAT,i);
   *tileLayer= load_bitmap(c,NULL); 
}

loadTilemap(s_world->tilemap, &TileMap); 

That's assuming TileMap is of type BITMAP *.

Alternatively, you could simply return the BITMAP* pointer as a result of loadTilemap:

 BITMAP* loadTilemap(int i,BITMAP * tileLayer){
   char c[128];
   sprintf(c,TILEPATHFORMAT,i);
   return load_bitmap(c,NULL); 
}

TileMap = loadTilemap(s_world->tilemap, TileMap);

This would allow you to get rid of tileLayer parameter altogether, as you don't seem to be using it for anything else in loadTileMap (i.e. it's only an output parameter).


Try this:

void loadTilemap(int i,BITMAP ** tileLayer){
    char c[128];
    sprintf(c,TILEPATHFORMAT,i);
    *tileLayer = load_bitmap(c,NULL);
}


loadTilemap(s_world->tilemap, &TileMap); 

The problem was that you pass the pointer to the BITMAP by value. To get the new pointer value out of loadTilemap, you have to pass it by reference.

EDIT:

On the other hand: why don't you just return the pointer to the newly created BITMAP?

BITMAP * loadTilemap(int i* tileLayer){
    char c[128];
    sprintf(c,TILEPATHFORMAT,i);
    return load_bitmap(c,NULL);
}

...

TileMap = loadTilemap(s_world->tilemap);
0

精彩评论

暂无评论...
验证码 换一张
取 消