Glitch in Creating Vectors within C++ class?

Hello! I have come across a very strange error when working with pointers to 2d vectors within C++ classes, when I create the vectors in a function and assign the object member variable to point to that new 2d vector, then call the .data() function on that class member pointer to move the data to an array, the first element of the array is nonsense and the rest are normal. Or maybe the first element picks up an address somewhere and thinks that the first element? Either way I think its a error, if anyone has a pointer trick to get around this that would be awesome! Thanks so much! (I compile with pgc++)
Side note: this is not a problem when the 2d vectors are not pointers in the Rectangle class for some reason

#include
#include
#include

using namespace std;

class Rectangle {
public:
std::vector< std::vector > *objvec; // pointer, constructed in transfer()
std::vector< std::vector > *objvec_2; // pointer, constructed in main
double ** temp;
double ** temp_2;

void transfer();

};

void Rectangle::transfer(){

std::vector v_fill(10, 5);
std::vector< std::vector > v(10, v_fill);

objvec = &v;

temp = new double*[10];

for (int i = 0; i < 10; i++){
temp = (objvec).data();
}

std::cout << “In Transfer with temp” << std::endl;
for (int x = 0; x < 10; x++){
for (int y = 0; y < 10; y ++){
std::cout << temp[x][y] << " ";
}
std::cout << std::endl;
} // prints normally as it should

}

int main()
{
Rectangle obj;

obj.transfer();

std::cout << “in Main with temp” << std::endl;

for (int x = 0; x < 10; x++){
for (int y = 0; y < 10; y ++){
std::cout << obj.temp[x][y] << " ";
}
std::cout << std::endl;
} // Prints incorrectly


// below is temp_2 with the same construction that caused the problem in array temp but entirely in Main,
// and its values are correct…
std::vector v2_fill(10, 5);
std::vector< std::vector > v2(10, v2_fill);

obj.objvec_2 = &v2;

obj.temp_2 = new double
[10];

for (int i = 0; i < 10; i++){
obj.temp_2 = (*obj.objvec_2).data();
}

std::cout << “in Main with temp_2” << std::endl;

for (int x = 0; x < 10; x++){
for (int y = 0; y < 10; y ++){
std::cout << obj.temp_2[x][y] << " ";
}
std::cout << std::endl;
} // Prints correctly

std::cout << “Done” << std::endl;

}

Hi Matt,

I can’t compile this code due to syntax errors so assume that this isn’t your full example and just a cut-down version.

Though I think the main problem (as you describe it) is that “v” and “v_fill” are local variables within “transfer” and hence get destroyed once they are out of scope. You would need to declare these to be global, in main and then pass them into transfer, or dynamically allocate them in “transfer” so they don’t get destroyed.

-Mat

Hi Mat, Thank you that was the problem!! Sorry about the non-runnable code.

Thanks again!