Thread: Dynamic Memory Allocation?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Code:
    #include <iostream>
    using namespace std;
    
    int main(void)
    {
      int numelements;
      int *pArray=0;
      cout<<"Enter the number of array elements:";
      cin>>numelements;
      pArray=new int[numelements];
      //of course when you're done with them
      if(pArray)
      {
        if(numelements>1)
        {
           delete [] pArray;
        }
        else if(numelements==1)
        {
          delete pArray;
        }
        pArray=0;
      }
      return(0);
    }
    To change the size on the fly, you'd want to have another pointer which you'd dynamically allocate to be the size of your original array. Then copy the contents of your original array into the temp secondary array. Next clean up your original array (delete + set it to NULL). Reallocate your original array to the new size. Copy the first group of array elements being stored in the temp array into the first part of the newly reallocated array. Finally clean up the temp secondary array.

    Of course, std::vector's are allowed to grow dynamically, so you may want to look into them.
    Last edited by jdinger; 12-02-2002 at 08:30 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  4. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM