Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Allocating space for matrix M[][] in c++

matrix

  • Please log in to reply
3 replies to this topic

#1 Agent001

Agent001

    CC Regular

  • Member
  • PipPipPip
  • 41 posts

Posted 05 November 2012 - 03:17 PM

I need to create a class with a matrix, and to allocate space for it using a constructor.

Would this code work

class Matrix {
    int **m;
    int r, c;

public:
    Matrix(int rr=3, int cc=4){
        m = new int[r = rr];
        for (int i = 0; i<r; i++)m[i] = new int[c = cc];
    }
}

Is this correct? And how would a proper destructor look?
  • 0

#2 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 05 November 2012 - 03:30 PM

Why do you have r = rr inside the new statement? That's confusing and doesn't make sense. Also, you should change that to int*[rr], not int[rr]. You're allocating an array of pointers to arrays.
  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'


#3 Agent001

Agent001

    CC Regular

  • Member
  • PipPipPip
  • 41 posts

Posted 06 November 2012 - 04:59 AM

Why do you have r = rr inside the new statement? That's confusing and doesn't make sense. Also, you should change that to int*[rr], not int[rr]. You're allocating an array of pointers to arrays.


I have default values for rows and columns.

But, i want the user to enter the dimensions from the main program, and if he doesn't, the matrix with the default dimensions would be displayed.

Also, a little help with the destructor would be appreciated :)
  • 0

#4 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 07 November 2012 - 11:42 PM

Well, you can have r = rr before you allocate - that's more standard and readable. As for your destructor, just iterate through the array and delete each entry with delete [] blah. Don't forget the [] because you're deleting an array, not a single object. Bad things can happen otherwise.
  • 0

sudo rm -rf / && echo $'Sanitize your inputs!'






Also tagged with one or more of these keywords: matrix

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download