Dynamic 3D Arrays

Started by
4 comments, last by the_edd 16 years, 11 months ago
I'm trying to create a 3D array dynamically but I'm having some trouble with that. I can't figure out what I'm doing wrong here: int*** ImageData = new int[IMAGE_SIZE]; for(int i = 0; i < IMAGE_SIZE; i++) { ImageData = new int[IMAGE_SIZE]; for(int j = 0; j < IMAGE_SIZE; j++) { ImageData[j] = new int[3]; } } Can someone help?
Advertisement
Quote:Original post by AltecZZ
Can someone help?

Should be something more like
int *** ImageData = new int ** [IMAGE_SIZE];for( int i = 0; i < IMAGE_SIZE; i++ ){	ImageData = new int * [IMAGE_SIZE];	for( int j = 0; j < IMAGE_SIZE; j++ )		ImageData[j] = new int[3];}


At the beginning, you have a pointer to an array of double pointer to integers, but then you're just making an array of straight integers. You should be making an array of double pointers to integers. Similar for the next one.
What you are doing there is creating a pointer to a pointer to a pointer, and then assigning integers to it, causing an error.
The way to create a dynamic three dimensional array is to call new int** and new int* to create arrays of pointers.

Thus:
[SOURCE]int main(){    int *** array;    array = new int**[IMAGE_SIZE]; //Creates an array of pointers to pointers.    for (int i = 0; i < IMAGE_SIZE; ++i)    {        array = new int*[IMAGE_SIZE]; //Creates an array of pointers        for (int j = 0 ; j < IMAGE_SIZE; ++j)        {            array[j] = new int[3]; //Creates the array.        }    }    //I'm not sure that this is the correct way to destroy these arrays.    //So if someone could correct this part,that would be amazing.    for (int i = 0; i < IMAGE_SIZE; ++i)    {        for (int j = 0; j < IMAGE_SIZE; ++j)        {            delete [] array[j];        }        delete [] array;    }    delete [] array;}

[size=1]Visit my website, rawrrawr.com

Ah, that makes more sense!

What if I wanted them to be unsigned?

I get this error on the first line:

unsigned int *** imageData = unsigned int ** [IMAGE_SIZE];

VS2005 complains about type 'unsigned int' unexpected
Quote:Original post by AltecZZ
I get this error on the first line:

unsigned int *** imageData = unsigned int ** [IMAGE_SIZE];

VS2005 complains about type 'unsigned int' unexpected

Try:

unsigned int *** imageData = new unsigned int ** [IMAGE_SIZE];
MumbleFuzz
If you're happy using boost in your project you could use boost::multi_array. All the memory management and exception safety issues have been thought through for you. You're also not restricted to 3D.

http://www.boost.org/libs/multi_array/doc/index.html

Edd

This topic is closed to new replies.

Advertisement