(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;
}
注意:我只是猜测这可能是您想要的。
相关文章:
- 保存/加载大量短数组到二进制文件
- 如何在数组和向量 c++ 中存储和保存输入
- 2D 数组,某些单元格保存特定数据
- 如何在c++中将字符串中的所有数字保存到多维数组中
- 将值更改为 c++ 的数组并保存文件
- 数组不保存初始化值
- 按顺序遍历 AVL 树,将值保存在数组中
- 将 QImage 保存到字节数组
- 将特征数组行保存在变量中
- 将 JPG 编码数组从 ROS sensor_msgs/压缩图像保存到 roscpp 中的文件
- C++ 如何动态保存大量数组?
- 在 tensorflow c++ api 中,如何从张量中保存图片或数组
- 获取C++中的多个输入文件并将其保存在数组中
- 生成唯一的随机字符并将其保存在数组中
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 如何在C++中保存动态数组中的值
- 如何将外部文件中的数据保存到 2D 数组中?(C++)
- GoogleMock SaveArg 用于保存数组?编译器抛出错误,我还没有看到一个好的解决方案
- 保存数组地址的指针的地址是相同的
- 在armadillo中保存数组(立方体)以便稍后在R中加载的最佳格式