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?
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?
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?
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?.
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