How do I pass a 2D array to a constuctor with variable dimensions?

I want to make a class that will allow me to create a "CharMap" object so I can output them (2D char arrays) a certain way. The class has the data members m_height, m_width, and the 2D character array.

Right now I'm creating the character array I want, then passing the constructor the width and height, but I don't know how to pass it the actual array ONLY because the height and width are variable.

I want to keep it as a character array because I can format it nicely, like this:

1
2
3
4
5
6
char myMap[5][10] = {
    {"+========+"},
    {"|        |"},
    {"|        |"},
    {"|        |"},
    {"+========+"} };


The problem is, if I try to pass that to, say, a function CharMap::setMap();, I need to tell it the height and width right? But if I set them to the data members "m_height" and "m_width", I want to use them in the function prototype to tell it how big of an array to get (as set by the constructor), but I can't use data members in the prototype it seems, since this gives me an error:

void setMap( myMap[m_height][m_width] );

I tried using pointers and char**, but I think I'm getting in too deep here, all I want to do is be able to pass an array (of variable height and width) to a function that will output it in a special way, rather than copying the code (for my special output) after each character array I create.
Hi There,

I am afraid that you cannot do this with basic types. You can however create an array class yourself to implement it the way you want to...
1
2
3
4
5
6
7
8
9
10
11
template<class T>
class Array
{
    public:
        // construct, copy, destroy and assign go here...
    private:
       // members...
       char* m_array;
       int m_dim1;
       int m_dim2;
};

Something like that should be roughly want you are after, but also take a look at the std::vector to see if this cannot fulfill your requirements.

Kind Regards,

Phil.
You can pass it as an array if you can specifiy the second dimension as a constant; the constructor would be class_name(int array[][10], int dim1). This doesn't seem too bad; it just requires a fixed line length essentially.

The second dimmension is required for the compiler to generate the proper code due to the way an array operator[] is translated into pointer derefrence operations. You can also do it with a pointer, but it is ugly. You essentially flatten it to a single dimension array and do the calculation yourself: in a nested loop over i and j, access element by array[i*dim2+j].

I would just recommend using vector<string> or just concatenate into a single string, if you can.
Topic archived. No new replies allowed.