问题
I have a Matrix class and I want to pass an array to the constructor in order to set the values of the matrix dynamically. I found that if I allocate an array like this:
double **array;
array = new double*[3];
array[0] = new double[2];
array[1] = new double[2];
array[2] = new double[2];
array[0][0] = 1;
array[0][1] = 1;
array[1][0] = 1;
array[1][1] = 1;
array[2][0] = 1;
array[2][1] = 1;
I can get the number of rows and cols using a method like this:
int getNRows(double **data){
int size = 0;
while(*(data+size)){size++;}
return size;
}
int getNCols(double **data){
int size = 0;
while(**(data+size)){size++;}
return size;
}
Is this ok or should I stick to the vector declaration?
回答1:
Your assumption is totally wrong; you cannot obtain the size in any way close to what you propose. That's utterly undefined and dangerous behaviour.
Here's a pseudo-rule (i.e. it's not true, but unless you understand why it's not true, it applies to you):
Don't use pointers. Don't use new and delete. (And don't say using namespace std;.)
The one and only way in which you should be doing this is with C++ containers.
A vector of vectors would be the first shot, though a flat vector accessed in strides may be better, and Boost.multi_array may even be the best:
std::vector< std::vector<double> > v (3, std::vector<double>(2));std::array<std::array<double, 2>, 3>std::vector<double> v(6);, and usev[i + 2 *j]etc.Boost.MultiArray
回答2:
You are relying on undefined behaviour; there is no guarantee what will happen when you exceed the bounds of an array. This will not work in general.
Use a std::vector, or another container class.
回答3:
If that works it's by pure luck. You don't know what is beyond the memory allocated for the matrix, and especially if its null.
Stick to something like:
std::vector<std::vector<double>> matrix;
回答4:
What happens when you store the value 0 in your array? You need to store and pass the sizes to functions that operate on your data structure, or use an STL container like std::vector.
Please pick up a copy of Effective STL.
Also, if you want to be more clear about why you need a multi-dimensional array, we may be able to propose a better solution.
来源:https://stackoverflow.com/questions/8320297/is-this-a-good-way-to-find-the-length-of-a-dynamically-allocated-array