简体   繁体   中英

Double size of dynamic array

I'm really not sure why this is not working. It is like the array size is not doubling. I'm sure what I'm missing is something simple, but I can't figure out why it is not functioning properly.

void add_element(int* &array, int &size , int &count)
{
    int tempp;
    cout << "What number do you want to add ? " << endl;
    cin >> tempp;
    int temp = size * 2;
    int *newArr;
    newArr = new int[temp];
    if(count ==  size)
    {
        for (int i = 0; i < size; i++)
        {
            newArr[i] = array[i];

        }
        size = temp;
        delete[] array;

        ++count;
        newArr[count] = tempp;

        array = newArr;
    }
}

Your function is not implemented correctly, not even close.

You should not be allocating a new array every time the function is called, only when the current array is not large enough to store the user's number.

If count and size are not the same value, you are leaking memory, and you are not inserting anything into the existing array.

You are touching the array only if count and size are the same value, but when you go to store the user's number into the new array, you are storing it at the wrong index.

Try this instead:

void add_element(int* &array, int &size, int &count)
{
    int number;
    cout << "What number do you want to add? " << endl;
    cin >> number;
    if (count == size)
    {
        int newSize = size * 2;
        int *newArr = new int[newSize];
        for (int i = 0; i < count; ++i)
        {
            newArr[i] = array[i];
        }
        delete[] array;
        array = newArr;
        size = newSize;
    }
    array[count] = number;
    ++count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM