改变数字的问题

时间:2015-01-21 04:56:09

标签: c++ arrays

寻找一些功课帮助。不仅仅是为了在正确的方向上轻推一个答案。我们给出了一个数组,其中包含一些数字,数组的大小以及我们将它加倍的次数。我们要将大小加倍,复制相同的数字,然后将后半数乘以2。

因此,如果数组为{0,1}且编号为2.最后一个数组为{0,1,0,2,0,2,0,4}。

我的代码正确编译并返回一些非常奇怪的数字,原始数组{0,1}和数字3给了我一堆0和中间的随机135057。

继承我的代码:

int *ArrayDynamicAllocation(int array[], int size, int number)
{
    for (int runs = 1;runs < number; runs++) {
        int new_size = size * 2;

        int *new_array = new int[new_size];

        for (int x = 0;x < size; x++) {
            new_array[x] = array[x];
        }

        for (int y = size+1; size < new_size; size++) {
            new_array[y] = array[y];
        }

        size = new_size;
        array = new_array;
        delete [] new_array;
    }
    return array;
}

1 个答案:

答案 0 :(得分:0)

正如@Elvisjames在评论中所说,array = new_array;表示您将指向新创建的new_array的内存的指针分配给array,而delete [] new_array;表示您正在删除两者来自记忆的new_arrayarray。由于之前的分配,array指向new_array,删除new_array表示删除array

首先删除旧数组然后将新创建的数组分配给旧数组。

在你的循环中:

for (int y = size+1; size < new_size; size++) 
{
     new_array[y] = array[y];
}

正如@Elvisjames在评论中所说,new_array[y] = array[y];没有array[y]

您应该将ArrayDynamicAllocation功能定义如下:

int *ArrayDynamicAllocation(int array[], int& size, int number)
{
    for (int runs = 1;runs < number; runs++) 
    {
        int new_size = size * 2;

        int *new_array = new int[new_size];

        for (int x = 0;x < size; x++) 
        {
            new_array[x] = array[x];
            new_array[x+size]=2*array[x];
        }

        size = new_size;

        // Here you should delete the old array first then assign the newly created array to the old array.
        //array = new_array;
        //delete [] new_array;  

        delete [] array;
        array = new_array;
    }
    return array;
}

我知道新尺寸后,已将int size更改为int& size