(c++)将main中的随机值保存到函数数组中

(c++) saving random value from main to a function array

本文关键字:保存 数组 函数 随机 c++ main      更新时间:2023-10-16

所以这是我应该做的,但它让我有点困惑,这是我到目前为止得到的任何帮助都将不胜感激:)

编写一个动态分配整数数组的函数。函数应接受一个整数参数,该参数指示要分配的元素数,并应返回一个指向数组的指针。然后在主函数中编写一个驱动程序,生成一个随机数(不太大的数字),调用该函数,并通过保存第一个元素的值并显示该元素的内容来验证访问权限。

它运行的是经过编辑的代码,但我觉得我根本没有使用我的函数。

#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);

int main()
{
    srand(time(0));
    int random = rand() % 5 + 1;
    const int size = 5;
    int array[size];
    MyArray(size);
   array[0] = random;
    cout << array[0] << endl;
}
int *MyArray(int numOfElements)
{
    int *array;
    array = new int[numOfElements];
    return array;
}

编辑代码

int main()
{
    srand(time(0));
    int random = rand() % 5 + 1;
    const int size = 5;
    int* array = MyArray(size);
    array[0] = random;
    cout << array[0] << endl;
    delete [] array;
}

我相信你会尝试这样做:

#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);

int main()
{
    srand(time(0));
    int random = rand() % 5 + 1;
    int *array = MyArray(random); //! store the pointer of dynamically allocated memory and use it.
    array[0] = random;
    cout << array[0] << endl;
    delete [] array; //! To avoid memory leak
}
int *MyArray(int numOfElements)
{
    int *array = new int[numOfElements];
    return array;
}

注意:我只是猜测这可能是您想要的。