动态数组的两倍大小 [英] Double size of dynamic array

查看:115
本文介绍了动态数组的两倍大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不确定为什么这行不通。就像数组大小没有增加一倍。我确定我所缺少的只是简单的东西,但我不知道为什么它无法正常运行。

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.

如果 count size 的值不相同,则是内存泄漏,没有在现有数组中插入任何内容。

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

仅在时才接触数组count size 是相同的值,但是当您将用户编号存储到新数组中时,会将其存储在错误的索引处

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.

尝试以下操作:

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

这篇关于动态数组的两倍大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆