Search code examples
c++arraysdynamic-memory-allocation

Appending to an array in Dynamic Memory


Using dynamic memory, I am trying to make a class that stores numbers in a dynamic array (so 123 would be arr[0] = 1, arr[1] = 2, arr[2] = 3) and be able to append digits (e.g. if the number stored is 123, you could add more digits.. 45 and the new number would be 12345).

Here's my code so far: How would I go about making an append function?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int *exampleArray; //new array into exsistence 

    exampleArray = new int[5]; // dynamically allocates an array of 5 ints
    for (int i = 1; i < 5; i++)
    {
        exampleArray[i] = i;
        cout << exampleArray[i] << endl;
    }

    delete exampleArray; // deleted from exsistence

    system("pause"); // to show the output
    return 0;
}

Solution

  • If you allocate an array with new[], the only way to "append" to it is to new[] a new array of larger size, copy the existing values from the old array into it, and then delete[] (not delete) the old array and update your array pointer to point at the new array.

    Also, note that arrays are 0-indexed. Your loop is not populating exampleArray[0] with any data.

    For example:

    int *arr = new int[3];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    
    ...
    
    int *newarr = new int[5];
    std::copy(arr, arr+3, newarr);
    newarr[3] = 4;
    newarr[4] = 5;
    delete[] arr;
    arr = newarr;
    
    ...
    
    delete[] arr;
    

    You can optimize this a little by pre-allocating more memory than you actually need, and only "grow" when you actually exceed that memory. For example:

    int *arr = NULL;
    int num = 0, cap = 0;
    
    void append(int digit)
    {
        if (num == cap)
        {
            int *newarr = new int[cap + 10];
            std::copy(arr, arr+num, newarr);
            delete[] arr;
            arr = newarr;
            cap += 10;
        }
    
        arr[num] = digit;
        ++num;
    }
    
    ...
    
    append(1);
    append(2);
    append(3);
    
    ...
    
    append(4);
    append(5);
    
    ...
    
    delete[] arr;
    

    That being said, what you are asking for would be best handled using std:vector instead. It is a dynamic-length container that handles these ugly details for you.

    For example:

    std::vector<int> arr;
    
    void append(int digit)
    {
        arr.push_back(digit);
    }
    
    ...
    
    append(1);
    append(2);
    append(3);
    
    ...
    
    append(4);
    append(5);
    
    ...