failing like never before

20Jan/080

Dynamically Create a Multidimensional Array

I had a few problems trying to dynamically create and pass a multidimensional array in C++ for my previous programming project. Of course, passing an array by value is rather ridiculous when the array is large, so I had to pass by reference. Now, passing a single dimensional array is really quite simple in C++, you just do the following:

//stuff
int input_cols;
char *char_array_ptr;
//stuff
cout << "cols? ";
cin >> input_a;
char_array_ptr = new char[input_cols];
return char_array_ptr;

And hey, you're done. The same thing could pretty much be done in C by using malloc, instead of new. But as I mentioned, I needed to pass a multidimensional array.

Trying a similar thing with a two-dimensional array did not work at all:

//stuff
int input_cols, input_rows;
char *char_array_ptr;
//stuff
cout << "cols? ";
cin >> input_cols;
cout << "rows? ";
cin >> input_rows;
char_array_ptr = new char[input_cols][input_rows];
return char_array_ptr;

At first I played with the thought of just creating another class, but decided that would be far too wasteful. I ended up doing what I now call, the "poor man's multidimensional array." Basically, instead of doing something like this:

char_array_ptr = new char[input_cols][input_rows];

I just did:

char_array_ptr = new char[ input_cols * input_rows ];

Which ended up working great, the only downside is that it isn't as intuitive (i.e. you wanted your data to represent a grid).

However, I later on figured out a more elegent solution. A two-dimensional array is essentially just a single-dimensional array of pointers, with each of those pointers pointing to a single-dimenionsal array of pointers. I realize it sounds a bit weird at first, but if you think about it for a while, it will start to make sense. So we can do the following:

char **char_array_ptrptr;
//pointer to a pointer
char_array_ptrptr = new char* [input_cols];
// allocate cols
for (int temp_rows = 0; temp_rows < input_rows; input_rows++)
{
char_array_ptrptr[temp_rows] = new char[input_rows];
} // allocate rows

I'm pretty proud of myself for figuring this out, but I'm sure its pretty elementary stuff

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


Security Code:

Trackbacks are disabled.