GP32 Loading A Map


dieu666

Still Fresh
Joined
Jan 22, 2004
Messages
29
here is my pb:
I made my own map struct for my game engine and it look like this:
typedef struct {
u8 *img;
}TILE;

typedef struct {
u16 xsize; //xsize and
u16 ysize; //ysize of the map
u16 nbr_tiles; //nbr of tiles in list_tiles
u16 nbr_sprites; //nbr of sprites in list_sprites

TILE *list_tiles; //list of the tiles
u16 ** tiles; //tile number (in list_tiles) of the tile in the map
SPRITE * list_sprites; //list of the sprites
u16 * sprites[2]; //sprite coord
}MAP;

and when I load the map with this function:
MAP * load_map(char * path);
I test each element of the MAP to be sure they're working and they are, but when i do:
map = load_map(map_path);
when loaded every element of the map is where it should be
but it's like if load_map() return a pointer to a wrong place (i can't access map's element)
here is the code to load the map:

MAP * load_map(char* path)
{
GPFILE *pf,*pf2;
MAP map;

int n,m;
char buffer[30];

smc_fread(&map.xsize,1,2,pf);
smc_fread(&map.ysize,1,2,pf);
smc_fread(&map.nbr_tiles,1,2,pf);
smc_fread(&map.nbr_sprites,1,2,pf);

map.tiles = (unsigned short**)malloc(map.xsize*sizeof(unsigned short*));
for(n = 0;n<map.xsize;n++)
*(map.tiles+n) = (unsigned short*)malloc(map.ysize*sizeof(unsigned short));
map.list_tiles = (TILE*)malloc(map.nbr_tiles * sizeof(TILE));
map.sprites[0] = (u16*)malloc(map.nbr_sprites * sizeof(u16));
map.sprites[1] = (u16*)malloc(map.nbr_sprites * sizeof(u16));

for(n=0,m=0;n<map.nbr_tiles;n++){ //read the tile's path so i can open it
while(fread(buffer+m,1,1,pf) && buffer[m++]!='\0');
pf2 = smc_fopen(buffer,"r");
load_tile(pf2,map.list_tiles+n);
smc_fclose(pf2);
gp_drawString(0,100,m,buffer,COLOR_RED,framebuffer[current_f]);
m = 0;
}

for(n=0;n<map.xsize;n++) //lit les numéro du tile ds la map
fread(map.tiles[n],2,map.ysize,pf);

smc_fclose(pf);
return &map;
}

I know this is a long code but i think i made a very stupid mistake somewhere but i can't find it. I didn't include all the code(would be too long) so i know this make things more difficult to help me but if you have any idea where could the problem be...

thanks in advance and sorry for my bad english

PS: if you know anything about how to improve my code don't hesitate to tell me too.
 
It's because you are declaring map in your function.

As soon as the function ends the storage for map is not valid.

You could define MAP *map=malloc(sizeof(MAP);

This way the storage for map will be in the heap.
 
Back
Top