Thread: Reducing the size of a dynamically allocated array?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    My comments:
    • Looking at your instructions, you don't need DisplayArray in the first place. You're supposed to print the second half of the dynamic array from the end each time and then copy the unprinted first half to another dynamic array, which means that by the end, you have a dynamic array of just one element that was already printed on the last iteration of the loop.
    • input is too generic a name; size or following your abbreviation arrSize would be more descriptive.
    • Declare variables near first use; in particular, it is best to declare them at the point where you can give them a meaningful initial value. So, instead of declaring currentArr and later assigning to it, just write:
      Code:
      int* currentArr = new int[input];
      Likewise, halfSize was better declared as in your post #1 rather than your post #3.
    • You need to update size with halfSize. I'm deliberately calling it size now because it is harder to reason about that when you call it input. Calling it size means you know it is the size of currentArr, and if you keep halving currentArr, clearly you need to keep halving size.
    • There is no need to first assign nullptr to a pointer when you're immediately going to assign another pointer to it.
    • Despite the reminder in your instructions, you forgot to delete[] currentArr when done with it.
    Last edited by laserlight; 11-09-2018 at 07:16 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of dynamically allocated block of memory
    By monkey_c_monkey in forum C++ Programming
    Replies: 12
    Last Post: 07-10-2012, 05:05 AM
  2. Replies: 8
    Last Post: 02-29-2012, 02:25 PM
  3. Dynamically Allocated Array
    By chris4 in forum C Programming
    Replies: 9
    Last Post: 05-06-2011, 10:01 AM
  4. Dynamically allocated array
    By dre in forum C Programming
    Replies: 17
    Last Post: 08-13-2009, 06:57 PM
  5. Dynamically allocated size
    By maverickbu in forum C++ Programming
    Replies: 12
    Last Post: 06-26-2007, 01:16 PM

Tags for this Thread