Thread: Dynamic Memory Allocation?

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    18

    Dynamic Memory Allocation?

    Can someone please give me some sample code on how I would be able to make an array of N elements. Where N is input by the user. I know a way of making say 'int num[100];' and when checking only checking until the counter variable equals N, but then wouldn't that waste the extra memory that was already allocated? Can you explain how after you input a number only allocate that many array elements? Or how about later on can you change the size of the array on the fly? Thanks again.
    Be yourself for those who mind don't matter, and those who matter don't mind.

  2. #2
    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.

  3. #3
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by jdinger
    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.
    You don't need that extra middle step. You are only allocating and deallocating an entire array for no reason.

    All you have to do is dynamically allocate an array of the new size that you want (not of the old one), then copy the data to the new array, then delete the old one. There is no need for a go-between. It only takes more code, more memory, and more processing time!

  4. #4
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    What are you talking about? Extra step?

    Then how do you know which array to use in the processing of the data in the main body of the program? If at the time you need to resize the array you toss the old array away and start using the new one, what happens when you need to resize the array again (another reason to just use vectors or a linked list).

    During the processing of your app's main functions you'll need to manipulate and extract data from an array. If you initialize the original array at start up then that's where you'll get the data for processing as the program is run. When you get to a point where you'd need to enlarge the array (from what you're suggesting) you'd simply allocate the second array and copy all the data into it and then clean up the first array. So now how does your app's main function now which variable name (array) to get it's data from? What you're suggesting makes no sense at all.

    I've already mentioned that resizing an array can be messy anyway and that's why using vectors would be much better (or better yet writing your own templated linked-list class).

  5. #5
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by jdinger
    What are you talking about? Extra step?

    Then how do you know which array to use in the processing of the data in the main body of the program? If at the time you need to resize the array you toss the old array away and start using the new one, what happens when you need to resize the array again (another reason to just use vectors or a linked list).

    During the processing of your app's main functions you'll need to manipulate and extract data from an array. If you initialize the original array at start up then that's where you'll get the data for processing as the program is run. When you get to a point where you'd need to enlarge the array (from what you're suggesting) you'd simply allocate the second array and copy all the data into it and then clean up the first array. So now how does your app's main function now which variable name (array) to get it's data from? What you're suggesting makes no sense at all.

    I've already mentioned that resizing an array can be messy anyway and that's why using vectors would be much better (or better yet writing your own templated linked-list class).
    Perhaps point the pointer to your old data at your new data?

  6. #6
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by jdinger
    So now how does your app's main function now which variable name (array) to get it's data from? What you're suggesting makes no sense at all.
    You just use a temporary pointer, you don't dynamically allocate an entire temporary array and copy everything over into it, that'd just be stupid.

    If you don't understand the simple concepts envolved with pointers and dynamic memory allocation then don't post about it!

  7. #7
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by Polymorphic OOP
    You just use a temporary pointer, you don't dynamically allocate an entire temporary array and copy everything over into it, that'd just be stupid.

    If you don't understand the simple concepts envolved with pointers and dynamic memory allocation then don't post about it!
    Man, that's funny. I am so humbled..../end sarcasm

    anyhoo, so you have your uninitialized temporary pointer point to the data in the array that you're going to delete then reallocate? so what do you think your temp pointer is pointing to then?

    I understand using a temporary pointer to pass it into. But from what I'm reading from your first post your saying that you are allocating a new array and cleaning up the old one.

    You obviously didn't read my earlier reply. I'm not talking about where the data is during the transfer, but how your functions know which array to grab the data from.

    Maybe it's just been a long day maintaining a bunch of crappy, legacy code and my braincells are mush, so I'll break it down to you.

    From what I get from what you originally wrote...

    All you have to do is dynamically allocate an array of the new size that you want (not of the old one), then copy the data to the new array, then delete the old one.
    Code:
    //semi-pseudo
    
    array arrayOne, arrayTwo;
    
    void InitFunction()
    {
       arrayOne=new WhateverVarOrStruct[InitializedSize];
    }
    
    //here your app gets/sets data to/from your array
    void YourPrimaryFunction()
    {
        if UserPressedNkey
        {
          //ask for the new array size
          allocate arrayTwo the the new size;
          copy the data from arrayOne into arrayTwo;
          delete arrayOne;
        }   
        
        cout<<WhicheverArrayIsCurrent[0].int_member_var<<endl;
        //so how do we know that we are using arrayOne or arrayTwo
       //here?
    }
     
    int main(void)
    {
      while YouHaventQuitYet
      {
        YourPrimaryFunction();
      }
      return(0);
    }

  8. #8
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Here, I'm going to break it down EVEN further:

    You have a pointer to a dynamically allocated array and you want to make it point to one of of a new size with the same data.

    So, you make a temporary pointer.

    Dynamically allocate an array of the new size and store it's location to the temporary pointer.

    Copy the data from the original array to the new array.

    delete the data from the original array.

    Make the original pointer point to the new memory.

    There is no need for a temporary array -- only a temporary pointer.

    Code:
    int* MyArray;
    
    MyArray = new int[5];
    
    // Then use the array, set values, etc.
    
    int* TempPointer = new int[10];
    
    for( int i = 0; i < 5; i++ )
        TempPointer[i] = MyArray[i];
    
    delete [] MyArray;
    
    MyArray = TempPointer;
    See? No temporary array. Sorry if I sounded like a prick, but after I explain the reasoning quite clearly and you claim "it makes no sense" it brings me to the conclussion that either you didn't read it or you don't understand the concept of pointers.

  9. #9
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by Polymorphic OOP
    See? No temporary array. Sorry if I sounded like a prick, but after I explain the reasoning quite clearly and you claim "it makes no sense" it brings me to the conclussion that either you didn't read it or you don't understand the concept of pointers.
    Or that I spent the day trying to hack my way through a 350,000 line app that should have been shot at birth and saved of it's current misery and I until I get some much-needed sleep my brain is gel. :there'snosmileythatlooksliketheburntoutcrackheadi feellike:

    Sorry if I came off the wrong way at all, either. Didn't mean too. I understand what you're saying, I just didn't read that from your first post.

  10. #10
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    K, and again, sorry about being a prick earlier as well. After re-reading it I understand I came off a bit harsh.

  11. #11
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    another thing.....
    what is this???
    Code:
    if(pArray)
      {
        if(numelements>1)
        {
           delete [] pArray;
        }
        else if(numelements==1)
        {
          delete pArray;
        }
        pArray=0;
      }
    That dynamic memory was obtained with new[] so should be deleted with delete[] even if there is only 1 element. You may or may not get away with this depending on exactly how your compile implements the new operator but whatever the code reads awfully.
    Simple to remember....
    if you use new then use delete.
    if you use new[] then use delete[]

    Always use the corresponding form.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  12. #12
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Thanks for catching that, SC. I should be ashamed, since I own a copy of "Essential C++".

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