Advertisement

Memory allocation question

Started by March 01, 2001 10:41 AM
1 comment, last by El Duderino 23 years, 11 months ago
Hello, thanks for looking at this. The problem is this struct
  
	struct stIsland
	{
	int tileid;
	int numofplants;
	int plants[30];
	int xoffset[30];
	int yoffset[30];
	int quad[30];
	BOOL flower;
	BOOL waterlily;
	BOOL tussock;
	BOOL palm;
	BOOL chilli;
	};

	stIsland Island [64][64];
  
It is popping the stack at runtime because I am too lame to allocate it any memory. I''m using C, no C++, except when addressing Direct X Can someone please explain to me how to allocate memory for this struct, using calloc, new, anything !! El Duderino
Not sure what you want to allocate... You want to allocate an array of [64][64]?
In that case (Using C++'s operators):

    int no1=64; // size of "main" arrayint no2=64; // size of "secondary" arraystIsland **Island = NULL; // Make a new pointerIsland = new stIsland*[no1];for (int index=0;index < no1;index++) Island[index] = new stIsland[no2];// and now to deallocate the memory...for (int index=0;index < no1;index++) delete [] Island[index];delete [] Island; // Delete what's left    


Remember that no1 and no2 are variables and don't have to be 64.


- Goblineye Entertainment
The road to success is always under construction

Edited by - Tornado on March 1, 2001 12:10:41 PM
Goblineye EntertainmentThe road to success is always under construction
Advertisement
Using malloc, you can do it this way:
stIsland *island = (stIsland *) malloc (64 * 64 * sizeof (stIsland));

The trick is that now stIsland is a single array of 4096 (64 * 64) elements, so you'll have to calculate row and offset on your own. In other words, you can't do:
island[x][y]

You'll have to do:
island[x * 64 + y]

Of course, you'll have to free it at the end of the program like this:
free (island);

Now, you can get a 2d array this way:
stIsland **island = (stIsland**) malloc (64 * sizeof (stIsland *));
int row;
for (row=0; row<64; ++row)
{
stIsland[row] = (stIsland*) malloc (64 * sizeof (stIsland));
}

And you'll have to free them in a similar way. This allocates an array pointers to arrays (your columns), and then allocates an array for each of those pointers (your rows). Now you can do:
stIsland[x][y]

and have it work.

The first method will give you a single contiguous block of memory, whereas the second method gives you a block of 64 pointers, and then 64 blocks of memory size 64*sizeof(stIsland) long.

BTW, regarding stIsland--you might want to cut down on the size of that mofo. BOOL is defined as int, I believe, and will cost you 32 bits each. Try using bitmasks instead. Also, make sure you need 32 bits for each of those ints--some might be better implemented as shorts or chars. Since you're going to be carrying around 4096 of these (and possibly more in the future?) every byte counts.

Good luck.

Edited by - Stoffel on March 1, 2001 12:48:41 PM

This topic is closed to new replies.

Advertisement