Resizing dynamic array?

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
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
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;
}

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
closed account (z05DSL3A)
Do not mix newed stuff with realloc
http://www.research.att.com/%7Ebs/bs_faq2.html#realloc
Last edited on
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.

Thanks for all the answers, ill be using the realloc solution for my program.
Works great.
Oh yeah, I should not use a new with a malloc. sorry...
Topic archived. No new replies allowed.