Thread: Dynamically Expanding an Array

  1. #1
    Registered User Vespasian's Avatar
    Join Date
    Aug 2011
    Posts
    181

    Dynamically Expanding an Array

    Consider the following:

    Code:
    int *p;
    p = new int[5];
    for(int i=0;i<5;i++)
       *(p+i)=i;
    Now suppose we want to add a 6th element (without using vector)

    One way is to copy it across to a larger array:

    Code:
    int *p;
    p = new int[5];
    for(int i=0;i<5;i++)
       *(p+i)=i;
    
    // realloc
    int* temp = new int[6];
    std::copy(p, p + 5, temp);
    delete [] p;
    p = temp;
    This looks like a very expensive operation and im looking for other ways.

    Three questions regarding the above:
    1. Not using vector, is this the best way to do this?
    2. What about using realloc? How would I use realloc in this situation?
    3. Any other ways apart from realloc or vector?
    Last edited by Vespasian; 05-28-2013 at 06:51 AM.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    if you were talking about objects that do a lot of work in their (copy) constructors, or that contain a lot of member data (large buffers, etc.), I'd agree that it would be pretty expensive, but int is not a type that is especially expensive to copy.


    to answer your questions:
    1. yes.
    2. don't use calloc/malloc/realloc/free in a C++ program, as there is no guarantee that it will cooperate properly with other things using new/delete.
    3. I can't think of any that are better than what you've got there.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array Expanding
    By Mcdom34 in forum C Programming
    Replies: 1
    Last Post: 06-26-2012, 10:59 PM
  2. Dynamically Allocated Array
    By chris4 in forum C Programming
    Replies: 9
    Last Post: 05-06-2011, 10:01 AM
  3. Dynamically allocated array
    By dre in forum C Programming
    Replies: 17
    Last Post: 08-13-2009, 06:57 PM
  4. Dynamically Allocating a 2D Array.
    By LightsOut06 in forum C Programming
    Replies: 17
    Last Post: 10-09-2005, 12:55 AM
  5. Code: An auto expanding array (or how to use gets() safely).
    By anonytmouse in forum Windows Programming
    Replies: 0
    Last Post: 08-10-2004, 12:13 AM

Tags for this Thread