home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c++:16175 comp.lang.c:16419
- Newsgroups: comp.lang.c++,comp.lang.c
- Path: sparky!uunet!rational.com!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Subject: Re: Delete a dynamically allocated 2-dim'l array?
- Message-ID: <rmartin.721612448@thor>
- Keywords: new, delete, dynamic array
- Sender: news@rational.com
- Organization: Rational
- References: <BxM7EC.BvE@math.uwaterloo.ca>
- Date: Thu, 12 Nov 1992 23:54:08 GMT
- Lines: 53
-
- xjzhu@math.uwaterloo.ca (Xiaojun Zhu) writes:
-
-
- |Q: How to delete a dynamically allocated 2-dimensional array?
- |
- |More specifically, I have:
-
- | int row, column;
- | int **array;
-
- |// stuff here to give values to row and column
-
- | array=new int*[row];
- | for(int i=0; i<row; i++)
- | array[i]=new int[column];
-
- |// now, I want to delete array, for example, in your destructor.
-
- |Can I simply say:
-
- | delete array;
-
- Nope. That won't work.
-
- |Or should I say:
-
- | for(i=row-1; i>=0; i--)
- | delete array[i];
- | delete array;
-
- This is better, and will likely work for "int **array", but will not
- work for "T **array" where T is a class with a destructor. Some
- compiler implementations may also fail even with "int **array".
-
- |Or, what should one do here? What would you do?
-
- for (i=0; i<row; i++)
- {
- delete [] array[i];
- }
- delete [] array;
-
- Similar in intent to your second example, but using the delete []
- syntax. Remember, you should always use delete [] if you use new T[].
- This will insure that all the destructors for the array elements are
- called, and that the proper amount of storage is returned to the heap.
-
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-