pointers - c++ two dimensional array question -


i create pointer 2 dimensional array of pointers (with width , height of x).
code expect? (create array elements, writing out information them, release allocated memory.)

int main(int argc, char** argv) {     int x = 3;     node ***array = new node**[x];     (int = 0; < 3; i++) {         array[i] = new node*[x];         (int j = 0; j < x; j++) {             array[i][j] = new node(i, j); /* node::node(int row, int col) */         }     }     /* ....... */     (int = 0; < x; i++) {         (int j = 0; j < x; j++) {             cout << array[i][j]->row << ", " << array[i][j]->col << endl;         }     }     /* ....... */     (int = 0; < x; i++) {         (int j = 0; j < x; j++) {             delete array[i][j];             //array[i][j] = null;         }         delete[] array[i];         //array[i] = null;     }     delete[] array;     //array = null;     return 0; } 

or should create vector of vector of pointers node objects?
or else should allocate objects on stack?

(i'm using pointers, because in java or c#, have use new keyword when creating object (however, don't think objects in heap memory), , read there more space available on heap.)

an other reason use pointers new keyword, create multiple pointers same object. should create 1 object on stack, , create pointers object?

i recommend use vector< vector<node> >, boost::multi_array, or can roll-up own dynamic 2d array class (it's not hard) wrapper around flat 1d std::vector.

all of above solutions store node objects in heap, , take care of cleaning memory.

here's example of simple matrix class wrapper around std::vector<t>:

#include <iostream> #include <vector>  template <class t> class matrix { public:     matrix() : width_(0), height_(0), vec_(0) {}      matrix(size_t width, size_t height)         : width_(width), height_(height), vec_(width*height) {}      size_t size() const {return vec_.size();}      size_t width() const {return width_;}      size_t height() const {return height_;}      // clears preexisting data     void resize(size_t width, size_t height)         {width_ = 0; height_ = 0; vec_.clear(); vec_.resize(width*height);}      void clear() {width_ = 0; height_ = 0; vec_.clear();}      t& operator()(size_t col, size_t row) {return vec_[row*width_ + col];}      const t& operator()(size_t col, size_t row) const         {return vec_[row*width_ + col];}  private:     size_t width_;     size_t height_;     std::vector<t> vec_; };  int main() {     matrix<double> a(3, 4);     a(1, 2) = 3.1415;     std::cout << a(1,2) << "\n"; } 

it uses operator() mimic array[2][4] syntax of c-style multidimensional arrays. don't have worry shallow copies, freeing memory, etc, because vector takes care of that.


Comments