繁体   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