pointer help

Started by
4 comments, last by xeddiex 18 years, 5 months ago
For some reason if i include this code my program crashes all its doing is creating an array of pointers then linking the pointers to another array. Wierd thing is if the level is only 5 columns along it works but anymore than that it crashes. The numbers look fine so i dont think its the text file has to be something im not aware of damn my noobness. thx alot for any help.

typedef struct Grid_tag{
	int Texture_id; //id of the grid texture
	int num_tiles;//number of tiles in the image
	int num_lvltiles; //number of tiles that make up the level

	Tile *Level; //stores pointers to the column tiles that make up the level
	Tile *tiles_data; //0's and 1's for each grid column
}Grid;

void Grid_LoadLVL(char *filename, Grid *g)
{
FILE *fp;
int i = 0;
int temp_id = 0;

fp = fopen(filename, "r");

fscanf(fp, "Total number of tiles used : %d\n", &g->num_lvltiles);

g->Level = (Tile*)malloc(g->num_lvltiles * sizeof(Tile*));

for(i=0; i < g->num_lvltiles; i++)
{
fscanf(fp, "%d ", &temp_id);

g->Level = g->tiles_data[temp_id];
g->Level.id = temp_id;
}

fclose(fp);

return;
}


Advertisement
Wtf if i add a printf in the for loop it all works arrrghhh.... lol

for(i=0; i < g->num_lvltiles; i++)
{
fscanf(fp, "%d ", &temp_id);

g->Level = g->tiles_data[temp_id];
g->Level.id = temp_id;
printf("huh %d \n", i); //WHAT THE HELL
}

anyone know why its being so strange?
Quote:Original post by fishleg003
For some reason if i include this code my program crashes all its doing is creating an array of pointers then linking the pointers to another array. Wierd thing is if the level is only 5 columns along it works but anymore than that it crashes.

The numbers look fine so i dont think its the text file has to be something im not aware of damn my noobness.

thx alot for any help.

*** Source Snippet Removed ***


I am sure it is this line right here;

g->Level = (Tile*)malloc(g->num_lvltiles * sizeof(Tile*));

here you are allocating memory for a tile pointer but you need to get memory that is the sizeof the tile struct times num_lvltiles not the size of a pointer times num_lvltiles so use sizeof(Tile) instead of sizeof(Tile*)
Gor435 - My Journal - MySpace - Facebook
Genious /kiss Gor435

Thx m8 how wierd is that tho it lets you off with writing 5 values to nothing and you can use them with a good old printf lol.
no problem thats what I am here for [smile]
Gor435 - My Journal - MySpace - Facebook
I would also like to point out another problem with this code, though, it's not the real problem:

g->Level = (Tile*)malloc(g->num_lvltiles * sizeof(Tile*));


In C, Casting the return value from malloc is unnecessary. It is pre-ANSI. it was used before the void* generic pointer type was made standard to silence warnings and whatnot but it is no longer needed.
one..

This topic is closed to new replies.

Advertisement