简体   繁体   English

动态数组的两倍大小

[英]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. 如果countsize不相同,则说明内存泄漏,并且没有在现有阵列中插入任何内容。

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. 仅当countsize是相同的值时,您才接触该数组,但是当您将用户号存储到新数组中时,会将其存储在错误的索引处。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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