home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / cplus / 16175 < prev    next >
Encoding:
Internet Message Format  |  1992-11-12  |  1.8 KB

  1. Xref: sparky comp.lang.c++:16175 comp.lang.c:16419
  2. Newsgroups: comp.lang.c++,comp.lang.c
  3. Path: sparky!uunet!rational.com!thor!rmartin
  4. From: rmartin@thor.Rational.COM (Bob Martin)
  5. Subject: Re: Delete a dynamically allocated 2-dim'l array?
  6. Message-ID: <rmartin.721612448@thor>
  7. Keywords: new, delete, dynamic array
  8. Sender: news@rational.com
  9. Organization: Rational
  10. References: <BxM7EC.BvE@math.uwaterloo.ca>
  11. Date: Thu, 12 Nov 1992 23:54:08 GMT
  12. Lines: 53
  13.  
  14. xjzhu@math.uwaterloo.ca (Xiaojun Zhu) writes:
  15.  
  16.  
  17. |Q: How to delete a dynamically allocated 2-dimensional array?
  18. |More specifically, I have:
  19.  
  20. |   int row, column;
  21. |   int **array;
  22.  
  23. |// stuff here to give values to row and column
  24.  
  25. |   array=new int*[row];
  26. |   for(int i=0; i<row; i++)
  27. |      array[i]=new int[column];
  28.  
  29. |// now, I want to delete array, for example, in your destructor.
  30.  
  31. |Can I simply say:
  32.  
  33. |   delete array;
  34.  
  35. Nope.  That won't work.
  36.  
  37. |Or should I say:
  38.  
  39. |   for(i=row-1; i>=0; i--)
  40. |      delete array[i];
  41. |   delete array;
  42.  
  43. This is better, and will likely work for "int **array", but will not
  44. work for "T **array" where T is a class with a destructor.  Some
  45. compiler implementations may also fail even with "int **array".
  46.  
  47. |Or, what should one do here? What would you do?
  48.  
  49.     for (i=0; i<row; i++)
  50.     {
  51.         delete [] array[i];
  52.     }
  53.     delete [] array;
  54.  
  55. Similar in intent to your second example, but using the delete []
  56. syntax.  Remember, you should always use delete [] if you use new T[].
  57. This will insure that all the destructors for the array elements are
  58. called, and that the proper amount of storage is returned to the heap.
  59.  
  60.  
  61. --
  62. Robert Martin                        Training courses offered in:
  63. R. C. M. Consulting                       Object Oriented Analysis
  64. 2080 Cranbrook Rd.                        Object Oriented Design
  65. Green Oaks, Il 60048 (708) 918-1004       C++
  66.