-4

I am assigning memory to 2-d array for which,i know the depth

int *array[size];
for(int i=0;;i++)
{
   array[i]=new int[10];
}

Am I doing it right?

user1838070
  • 11
  • 1
  • 3
  • why not just wrap it in an object that has an `at` operatior, like the one vectors have? This way you don't have to have matrix aritmetiks all over your code. – Martin Kristiansen May 10 '13 at 21:01

3 Answers3

1

No, you need for(int i=0; i<size; i++) so that the loop only execute size times. But this is not the most elegant way to do this. In C++, it is recommended that we use STL vectors instead of arrays to avoid memory management:

vector<vector<int> > array;

See Using arrays or std::vectors in C++, what's the performance gap?

Community
  • 1
  • 1
Yang
  • 7,712
  • 9
  • 48
  • 65
  • @user1838070, Well, you should consider switching to something that will manage the memory for you, like `std::vector`. – chris May 10 '13 at 20:38
0

Do you want a dynamic 2d array or an array of pointers to the heap on the stack?

An array of pointers to the heap on the stack carry on as you are (as the other poster suggested).

For a dynamic 2d array How do I declare a 2d array in C++ using new?.

Community
  • 1
  • 1
OOhay
  • 61
  • 6
0

You really should not implement a matrix in that way -- really. unless the dimensions change, please don't.

A nicer way would be:

template<typename Ty>
class  matrix {
public:
  const unsigned dim_x, dim_y;

private:
  Ty* const data;

public:
  matrix(const unsigned dim_x, const unsigned  dim_y) 
    : dim_x(dim_x), dim_y(dim_y), data(new Ty[dim_x *dim_y])
  {}

  ~matrix() {
    delete[] data;
  }

  const Ty at(unsigned i, unsigned j) const {
    return data[i + j*dim_x];
  }

  Ty& at(unsigned i, unsigned j) {
    return data[i + j*dim_x];
  }
};

And then just access the data with the matrix class.

I wrote a blogpost i thingy about it here

Martin Kristiansen
  • 9,875
  • 10
  • 51
  • 83