基于函数返回的数组创建动态数组

Create dynamic array based on an array returned by a function

本文关键字:数组 创建 动态 返回 于函数 函数      更新时间:2023-10-16

我目前正在尝试学习C++,我正在做的一个训练练习要求我执行以下操作:

创建一个动态数组,向其添加 100 个 int 值。

编写一个函数来计算每个数组元素的平方,并将此 int 值保存为数组中的位置 100 + element_index。

目前,我已经创建了一个动态数组,并用伪随机值填充了它。我想做的是计算这些随机值的平方,并将它们"附加"在数组的末尾。

变量 firstArray 在前面定义,但设置为 100。

typedef int* intPtr;
...
...
srand((unsigned)time(0));
intPtr myArray;
myArray = new int[firstArray];
for (int i = 0; i < firstArray; i++)
    ptr[i] = (rand() % 10);

这将创建我的初始动态数组,并为数组中的每个位置提供一个介于 0 和 10 之间的随机值。

如果我不必使用函数,我可以轻松地创建一个新的动态数组,将前 100 个值复制到其中,然后计算平方并将它们放在末尾。我尝试为练习使用一些伪代码,但我不确定如何正确实现它。

Create dynamic array of size 100, called myArray
Fill each indexed location with a random value between 0 and 10
Pass the dynamic array into a function
Function creates a new dynamic array of size 200
The values on location 0-99 from myArray are copied over
Calculate the square of the value on location n, and write it to location n+100
Return the dynamic array
Delete [] myArray
Create new dynamic array of size 200, called myArray
Copy the values from the array returned by my function into myArray
Delete the array returned from my function

我的问题与将信息传递到函数中并返回新信息有关:

如何创建一个可以将动态数组传递到的函数,并让它返回另一个动态数组?

如果无法

回答这个问题,我也非常希望得到有关结构、问题中包含的信息的反馈,以及如果这不是正确的问题类型,以便我将来可以提出更好的问题。

采用动态数组并返回动态数组(整数)的函数将具有以下签名:

int* newArray(int* array, int size);

然后,实现将从以下内容开始:

int* newArray(int* array, int size)
{
    int* ret = new int[size * 2]; // double the size
    // stuff to populate ret
    return ret;
}
int* myBiggerArray = newArray(myArray, firstArray);
// use myBiggerArray
delete [] myBiggerArray;

另外,远离typedef诸如int*之类的事情。 int*已经足够清晰简洁了。

我没有看到任何需要分配两次数组的要求。您可以分配一次所有内存。

// Allocate all the memory.
intPtr myArray = new int[firstArray*2];
// Fill the first part with random numbers
for (int i = 0; i < firstArray; i++)
    ptr[i] = (rand() % 10);