Need help with array

If i have a number of numbers in the array 0)
and I declare pointer 1)
and I allocate dynamic memory here for my pointer 2)
and I allocate dynamic array for count + 1 Example 3)

How can I copy elements from original arrays to new allocated array?

Also how can I copy the address of newly allocated array to fExample pointer?

p.s 0) 1) 2) 3) 4) means the coded step for each sentence mentioned
    int count = 0; 0)
    Example* fExample = nullptr; 1)
    fExample = new Example[count]; 2)
    fExample = new Example[count+1]; 3)
Last edited on
this leaks memory. the memory allocated on step 2 is inaccessible after step 3 (you lost the pointer to that memory, and no longer have that address).

what you want is step 0.5 Example ptr2;
and change step 4 to ptr2 instead of fexample.
then you can copy ptr2 into fexample AFTER a call to delete to release the memory in the old fexample.

copy elements can be done several ways, the most basic is just a loop.

if you want to resize fexample, make it a vector instead. You could also use malloc and realloc from C, but that is horrid and to be avoided if at all possible. If you ever DO try to make your own resizing container, allocate a bunch each time you resize, one at a time will lead to major performance problems due to the iterative copies.

Last edited on
Topic archived. No new replies allowed.