使用指针用随机数填充数组

Filling an array with random numbers using a pointer

本文关键字:数组 填充 指针 随机数      更新时间:2023-10-16

你好,我正试图用指针用从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()中)。