繁体   English   中英

(C ++)将随机值从main保存到函数数组

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

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

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

编辑的代码可以运行,但是我感觉我根本不使用我的函数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM