Is this a good way to find the length of a dynamically allocated array?

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?

Answers


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 use v[i + 2 *j] etc.

  • Boost.MultiArray


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.


Need Your Help

playing a video into a listview in Android

android listview videoview

Something strange here, I am trying to play a video from a listview but the problem is the videoView is not even placed in the list. the stranger part is that I managed to do it twice before withou...

Why does this Django form rendering taking forever?

python django forms html-rendering

I have a ModelForm based on a gigantic 300 fields model. Actually one model with 150 fields inheriting from another one with 150 other.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.