| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Constructor Initialization Problem
I would like to use a vector of vectors to store a 2D array. I played around with it in a small test file which I have included below. The problem is how I create my vector of vectors in the initialization list I think. The program crashes in my destructor when I attempt to delete my dynamically allocated vectors. It works if I use 0-6 as the size of my dynamically allocated vector, but as soon as I make it 7 it crashes...
Code:
class temp
{
public:
temp();
~temp();
void print();
private:
vector< vector < int > > Vector2D;
};
temp::temp() : Vector2D(3, *(new vector < int > (7,2)))
{
cout << "Hello!" << endl;
}
temp::~temp()
{
for (int i=0; i < Vector2D.size(); i++)
{
cout << i << endl;
if (&(Vector2D[i]))
{
delete &(Vector2D[i]);
}
//Program crashes before FINAL done is printed!
cout << i << " Done " << endl;
}
}
void temp::print()
{
for (int i=0; i < Vector2D.size(); i++)
{
for (int j=0; j< Vector2D[i].size(); j++)
{
cout << Vector2D[i][j] << " ";
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
temp t;
t.print();
return 0;
}
|
|
#2
|
|||
|
|||
|
Code:
temp::temp() : Vector2D(3, *(new vector < int > (7,2)))
{
cout << "Hello!" << endl;
}
Clarification: What does "Vector2D(3, *(new vector < int > (7,2))) " mean ??? Is this statement trying to create a 2 D vector as a matrix of size 7 by 2 ????? Probably, when deallocating memory you have to first free memory from cells first and then the array of cells. Just as you free memory from a double pointer? Example: Let we have to createa 2D char array of size 10 by 5 i.e if char **p = new malloc( 10) ; //allocates memory to single row of ten cells. and //for ( i = 0 ; i < 5 ; i++) // *(p + i) = malloc( 5) ; //etc. Then for deallocation we reverse the loops.Just try to apply that and see if it helps you. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Constructor Initialization Problem |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|