Search code examples
c++sizedynamic-arrays

How to increment the size of Dynamic Array (C++) without knowing the original array size?


Say we have this for instance:

string* p;
p = new string[2];
p[0] = "Aa";
p[1] = "Bb";

What I understand: I need to create a temp dynamic array to store what p has, delete p, and then create a new p with a row 1 size bigger than temp, and then copy temp into p.

What I do not understand: How would I increase the size of p WITHOUT knowing the original rowsize (in this case 2) and still keep the original data. I've read about doing tricks such as (sizeof(array)/sizeof(dataType)), but since I have a dynamic array, I have no idea how to find it's size. realloc would format my original data, plus it acts funny with strings.

Just a heads up: I do not want to use any form of linked lists, vectors, or things of that nature.


Solution

  • You can do the following:

    string* p;
    p = new string[2];
    p[0] = "Aa";
    p[1] = "Bb";
    
    string* reallocated = new string[3];
    std::copy(p,p+2,reallocated); // Save your original values
    delete[] p; // release formerly allocated memory
    p = reallocated; // Assign newly allocated memory
    p[2] = "Cc"; // Add some additional element
    

    Anyhow, I can't see a point, to do this in preference of simply using a std::vector<std::string>>.