使用指针用随机数填充数组
Filling an array with random numbers using a pointer
你好,我正试图用指针用从1到50的随机数填充我的数组。当我尝试这样做时,程序会崩溃。这是声明。
populate(arraySize, numArray);
和代码
void populate(int size, int *ptr)
{
int counter = 0;
srand(unsigned(time(0)));
while (counter < size++)
{
ptr[counter] = (rand() % 50) + 1;
counter++;
}
}
代码中没有错误,当这个方法被称为
srand(unsigned(time(0)));
void populate(int size, int *ptr)
{
int counter = 0;
while (counter < size)
{
ptr[counter] = (rand() % 50) + 1;
counter++;
}
}
删除大小++并将其更改为大小。
另一个解决方案是
int randomNumber () { return (std::rand()%50 +1); }
void populate(int size, int * ptr)
{
std::srand ( unsigned ( std::time(0) ) );
std::generate (ptr,ptr+size-1, randomNumber);
}
假设在调用此函数之前,用户会进行一些范围验证。
我猜您正在尝试遍历数组。您编写了counter < size++
,这意味着在检查counter < size
之后递增size
(我想这是应该保存项目数的变量)。++
运算符不会为您提供另一个等于size + 1
的值;相反,它以与size = size + 1
相同的方式递增size
。因此,size
将随着counter
的增加而增加,索引最终将超出界限,程序在尝试写入该位置时将崩溃。
另外,从srand
开始,您只需要调用它一次(例如在您的main()
中)。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用用户输入在C++中正确填充2D数组
- 如何找到大小'x'数组是否完全填充,在C++?
- 如何正确填充在堆上分配的二维数组?
- 如何将零填充的多维数组传递给 C++ 中的函数?
- C++ 填充数组时遇到问题
- 数组填充了不正确的值
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 用数据填充未指定大小的数组
- C++填充多维标准::数组
- 如何在 c++ 上将一定大小的数组填充到另一个更大大小的数组中?
- 有没有办法使用数组填充向量?
- 如何使用 PPM 格式的 uchar* 数组填充 QPixmap
- 在C 中动态分配的数组填充
- 使用数组填充对称矩阵
- C++中的{0}数组填充赋值
- 如何在OpenCV中用OpenNi的deepPixel数组填充矩阵
- 按行、列或随机从数组填充矩阵时出现错误索引问题
- 如何加快非顺序数组填充
- 将数组填充到最大值(memcpy vs vector)