Sign in to follow this  

pointer to multidimensional array?

Recommended Posts

I want to be able to create a pointer to a multidimensional array of unknown size. I tried this but it doesn't seem to work. Is it even possible? int **array_ptr; int array[][] = {{0, 0, 0, 0,}, {0,0,0,0}}; array_ptr = array;

Share this post

Link to post
Share on other sites
It is not possible the way you are doing it. An array created using A a[ ][ ] is interpreted by the compiler as: a[ i ][ j ] = a[ i+j*w ] where w is the width of the array. Also, this means a is of type A*, not A**. Since there is no way to extract a "width" value from a pointer, you cannot use a pointer like this.

However, there are other ways to do this. You can:
1- store the width yourself

A * a = get2DArray( ); //use a function to get the array
a[ i + w*j ]; //instead of a[ i ][ j ]

2- allocate an array of arrays

A * intermediary = new Array[ h*w ];
A ** a = new Array[w];
// set a[ i ] to (&intermediary[ i*h ])
// so that a[ i ][ j ] == intermediary[ i*h+j ]
a[ i ][ j ];

3- use a vector of vectors

std::vector< std::vector< A > > a;
//initialize everything to the correct size: a of size w, a[ i ] to size h
a[ i ][ j ];

4- create a wrapper

//use an "A2D" class to wrap around A * a', modify operator()
a(i,j); // == a.a'[ i+(a.w)*j ] where a is an instance of A2D.

5- use boost::multi_array

// from here.

boost::multi_array< A,2 > a(boost::extents[ w ][ h ]);
a[ i ][ j ];

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this