簡體   English   中英

動態數組的兩倍大小

[英]Double size of dynamic array

我真的不確定為什么這不起作用。 就像數組大小沒有增加一倍。 我確定我缺少的是簡單的東西,但是我無法弄清楚為什么它不能正常運行。

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

您的功能未正確實現,甚至無法關閉。

僅當當前數組的大小不足以存儲用戶的號碼時,才應該在每次調用該函數時都不分配新的數組。

如果countsize不相同,則說明內存泄漏,並且沒有在現有陣列中插入任何內容。

僅當countsize是相同的值時,您才接觸該數組,但是當您將用戶號存儲到新數組中時,會將其存儲在錯誤的索引處。

嘗試以下方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM