Monday, May 24, 2010

How do you assign (new) and clear (delete) space for a dynamic table of pointers in C++?

For example, take the simplest case of a table of pointers to integers.





int **table;


int nbElems;





table = new int*[nbElems];


for (int i = 0; i %26lt; nbElems; ++i)


m_neighbors[i] = 0; // just null pointers for now





// use it





delete [] table;








This doesn't work. Any ideas?

How do you assign (new) and clear (delete) space for a dynamic table of pointers in C++?
First of all, what's the value of nbElems? You need to assign a value to it before using it.





Second, where have you declared m_neighbors before you used it in the for loop?





Third, to delete a table of pointers you have to delete the objects the pointers are pointing to then delete the table itself. Do the following:





for(int i = 0; i %26lt; nbElems; i++)


{


delete table[i];


table[i] = NULL;


}





delete [] table;





// I hope this helps

clematis

No comments:

Post a Comment