Multidimensional Dynamic array with objects

Hi, I'm having a little trouble trying to get this code to not return an error.

1
2
3
4
5
6
7
8
Sprite ** frontBuffer;

for (int y = 0; y < 36; y++) {
	frontBuffer[y] = new Sprite(tileset->getFilename(), 16, 6);
	for (int x = 0; x < 96; x++) {
		frontBuffer[y][x] = new Sprite(tileset->getFilename(), 16, 6);
	}
}


I'm trying to create a front buffer (for a 2D video game), and need these sprite objects be filled in the multidimensional dynamic array called "front buffer".

And how would I delete this memory when I'm done, This is the second time if ever worked with multidimensional dynamic memory.
it's hellish: http://cplusplus.com/forum/articles/17108/

You're also doing it wrong in that code snippit you posted. You'd probably need to do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Sprite*** p = new Sprite**[HEIGHT];

for(int y = 0; y < HEIGHT; ++y)
{
  p[y] = new Sprite*[WIDTH];
  for(int x = 0; x < WIDTH; ++x)
    p[y][x] = new Sprite( whatever, whatever, whatever );
}


//  then to clean up

for(int y = 0; y < HEIGHT; ++y)
{
  for(int x = 0; x < WIDTH; ++x)
    delete p[y][x];
  delete[] p[y];
}
delete p;
So let me get this straight, "p" is a pointer, which points to an array of pointers, and those pointers point to another array of more pointers, and those pointers point to the object "Sprite"?

O yea, the program froze up when trying to compile in MSVC9, I think I'm going to see if I can use a one dimensional array, might also end up using a lot less Sprite objects.
Last edited on
I don't know that cuddlebunniezzz12 needed a 3 d array. The original example was clearly wrong but how did you determine that he needed a 3d array?
how did you determine that he needed a 3d array?


It's not really a 3D array, it's a 2D array of pointers.

I opted for this instead of a 2D array of objects because he wasn't using the default ctor. If you have an array of objects you can only use the default ctor, so either he'd have to default construct objects then reinitialize them, or go the pointer route.

I went with the pointer route.
Topic archived. No new replies allowed.