简体   繁体   中英

Initializing Dynamic 2d array in c++

I have created the class and first constructor, but I don't know how to initialize 2d array to ref as asked in 2, need to do this using dynamic memory allocation.

Create a class named matrix having followed private members:

• int **p;

• int rows;

• int cols;

The class should have the following member functions:

  1. matrix () initializes the 2d array to zero. Assume rows = 2 and cols = 2
  2. matrix (int **ref, int r, int c) initializes the 2d array to ref

MY CODE:


class Matrix
{
    private:
        int **p;
        int rows;
        int cols;
    public:
        // CONSTRUCTORS
        Matrix()
        {
            rows = 2;
            cols = 2;
            p = new int*[2];
            // initialize the array with 2x2 size
            for (int i=0; i<2; i++)
            {
                p[i] = new int[2];
            }
            //  taking input for the array
            for (int i=0; i<2; i++)
            {
                for (int j=0; j<2; j++)
                {   
                    p[i][j] = 0;
                }
            }


        }; 
        
        Matrix(int **ref, int r, int c)
        {
            rows = r;
            cols = c;
            p = new int*[rows];
            // initialize the array with 2x2 size
            for (int i=0; i<rows; i++)
            {
                p[i] = new int[cols];
            }
            //  taking input for the array
            for (int i=0; i<rows; i++)
            {
                for (int j=0; j<cols; j++)
                {   
                    p[i][j] = **ref;
                }
            }
        }

        friend ostream& operator << (ostream& output, Matrix& obj)
        {
            output << obj.rows;
            cout << " = ROWS" << endl;
            output << obj.cols;
            cout << " = columns" << endl;
            for (int i=0; i<obj.rows; i++)
            {
                for(int j=0; j<obj.cols;j++)
                {
                    cout << obj.p[i][j] << " " ;
                }
                cout << endl;
            }
            return output;
        }
};

int main()
{
    Matrix a;
    cout << a << endl;
    return 0;
}

It seems p[i][j] = **ref; should be p[i][j] = ref[i][j]; .

Also you should follow The Rule of Three . In other words, you should declare copy constructor and assignment operator to handle object (including pointers) copying properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM