动态数组和重复值

时间:2017-08-04 20:46:05

标签: c++ arrays dynamic allocation

我很难理解我哪里出错了。我的目标是将数组的大小加倍,并将原始值复制两次到新数组。目前这只是打印出6个零。请帮忙!!

#include <iostream> 
using namespace std;

void repeatArray(double *&myArray, int size)
{
        double *repeatArray = new double[size * 2]; 

        for(int i =0; i < size; i++)
        {
                 myArray[i] = repeatArray[i]; 
        }

        delete [] myArray;
        myArray = repeatArray;  
}

int main()
{
    double* myArray = new double[3];
    myArray[0] = 1;
    myArray[1] = 2;
    myArray[2] =3;
    repeatArray(myArray, 3);

    for (int i=0; i<6; i++)
    {
        cout << myArray[i] << endl;
    }
    delete []myArray;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

myArray[i] = repeatArray[i];错了。它应该是repeatArray函数中的repeatArray[i] = myArray[i];

好吧我错过了两次副本..

void repeatArray(double *&myArray, int size)
{
        double *repeatArray = new double[size * 2]; 

        for(int i =0; i < size; i++)
        {
                 repeatArray[i] = myArray[i];
                 repeatArray[i+size] = myArray[i];
        }

        delete [] myArray;
        myArray = repeatArray;  
}

这会在核心上复制这些值并让它过两次

答案 1 :(得分:0)

for(int i =0; i < *size*; i++)
        {
                 myArray[i] = repeatArray[i]; 
        }

您的程序只打印3个值,因为您没有为新数组指定正确的值。问题是你循环旧的大小,而不是大小* 2.

您可以这样处理:

for (int i = 0; i < size * 2; i++)
{
    // The first part of the array
    if (i < size)
    {
        // Copy values from another array
        repeatArray[i] = myArray[i];
    }
    // The second part of the array
    else
    {
        // Copy valeus from the first part
        repeatArray[i] = myArray[i - size];
    }
}