0

I want to create a distance matrix of a big dataset, and only want to store the 'close' enough elements. The code reads like this

vector<double> * D; 
D = (vector<double> *) malloc(dim *sizeof(vector<double>) ) ;

for(i=0;i<dim;i++){
    for(j=i+1;j<dim;j++){
        dx = s[j][0] - s[i][0];
        dy = s[j][1] - s[i][1];
        d =   sqrt( dx*dx + dy*dy );
        if(d  < MAX_DISTANCE){
            D[i].push_back(d);
            D[j].push_back(d);
            }
        }

which gives me segmentation fault. I guess I have not defined the array of vector correctly. How do I get around this ?

Duccio Piovani
  • 1,410
  • 2
  • 15
  • 27

1 Answers1

4

In C++ you should never allocate object (or arrays of objects) using malloc. While malloc is good at allocating memory, that's all it does. What it doesn't do is calling constructors which means all your vector objects are uninitialized. Using them will lead to undefined behavior.

If you want to allocate an array dynamically you must use new[]. Or, better yet, use std::vector (yes, you can have a vector of vectors, std::vector<std::vector<double>> is fine).


Using the right vector constructor you can initialize a vector of a specific size:

// Create the outer vector containing `dim` elements
std::vector<std::vector<double>> D(dim);

After the above you can use the existing loops like before.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks Joachim. The reason I want to use the and array is for the cycle and make j start at i instead of 0. With a vector I can't do it (ora at least I wouldn't know how.) – Duccio Piovani Apr 08 '16 at 10:52
  • @DuccioPiovani You should read on how to [resize](http://en.cppreference.com/w/cpp/container/vector/resize) the vector to the size you want, even if you knew nothing about the constructor. – PaulMcKenzie Apr 08 '16 at 10:58
  • @Joachim Pileborg this was very useful. Just made me save a lot of time. I thank you very much for that. – Duccio Piovani Apr 08 '16 at 10:59