Resizing dynamic array?

May 18, 2009 at 1:34pm
how do I resize dynamic array without using loop? (And I dont want too use std::vector).

loop version:
1
2
3
4
5
6
7
8
9
10
11
12
13
int size = 10;
int* arr = new int[size];

void resize()
{
   int* resize_arr = new int[size + 1];
   for(int i = 0; i < size; i++)
        resize_arr[i] = arr[i];

   size++;
   arr = resize_arr;
   delete[] resize_arr;
}


can I make this function faster, probably without loops? then how?

thanks in advance.
Last edited on May 18, 2009 at 1:51pm
May 18, 2009 at 1:52pm
closed account (S6k9GNh0)
If I remember, there are ways you can allocate space to an array but I'd have to look it up and it's not very clean if I remember correctly or too common.

EDIT: Apparently it was a hack using malloc...Go with vector :/
Last edited on May 18, 2009 at 1:55pm
May 18, 2009 at 2:17pm
Use memcpy to copy the memory more efficiently. And it's wasteful to only add one element when resizing. It's better to double it. And you're deleting the array you just allocated in the last line! Try something like this:

1
2
3
4
5
6
7
8
9
10
void resize() {
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}

May 18, 2009 at 2:28pm
1
2
3
4
5
int * pArray = new int[10];
void resize(size_t newSize)
{
    int * pArray = (int *) realloc(pArray, newSize);
}


I think this acts weird when pArray is NULL and/or newSize is zero. I forget what happens but it screwed me up once.


Last edited on May 18, 2009 at 3:22pm
May 18, 2009 at 2:38pm
closed account (z05DSL3A)
Do not mix newed stuff with realloc
http://www.research.att.com/%7Ebs/bs_faq2.html#realloc
Last edited on May 18, 2009 at 2:40pm
May 18, 2009 at 2:41pm
std::copy() should be preferred to realloc and memcpy for C++ apps, particularly because neither of the above are safe for arrays of objects (POD types are fine though). Although at that point, for large sizes, I'd use a deque.

May 18, 2009 at 2:43pm
Thanks for all the answers, ill be using the realloc solution for my program.
Works great.
May 18, 2009 at 3:23pm
Oh yeah, I should not use a new with a malloc. sorry...
Topic archived. No new replies allowed.