Dynamic array without loop and vector.

Hi there!
I'm sorry for my English, it is not my native language.
I have some problem with dynamic array.
I have this code

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

I would like to apdat code for beginner, expecially this part of code:
1
2
3
4
5
6
7
8
9
{
   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;
}

Thanks a lot!
closed account (48T7M4Gy)
Might be useful, particularly std::copy for the reasons given.

http://stackoverflow.com/questions/4729046/memcpy-vs-for-loop-whats-the-proper-way-to-copy-an-array-from-a-pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Double the size of an array

#include <iostream>

void display( int *anArray, int aSize)
{
    for(int i = 0; i < aSize; i++)
    std::cout << i << '\t' << anArray[i] << '\n';
}

int main()
{
    int size = 0;
    int new_size = 0;
    
    // CREATE AND POPULATE AN ARRAY
    std::cout << "Please enter size of array: ";
    std::cin >> size;
    
    int *array = new int[size]{0};
    
    for(int i = 0; i < size; i++)
        array[i] = i * i + 1;
    
    new_size = size * 2;
    
    // CREATE LARGER ARRAY
    int *resize_array = new int[new_size]{0};
    std::copy(&array[0], &array[size], resize_array);
    delete [] array;
    
    display(resize_array, new_size);
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.