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

时间:2015-02-10 07:13:18

标签: c++ arrays pointers crash

你好我试图用指针填充我的数组从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++;
}

}

代码没有错误,只有在调用此方法时才会运行它

3 个答案:

答案 0 :(得分:1)

srand(unsigned(time(0)));
void populate(int size, int *ptr)
{
int counter = 0;

while (counter < size)
{
    ptr[counter] = (rand() % 50) + 1;
    counter++;
}

}

删除大小++并将其更改为大小。

答案 1 :(得分:0)

另一个解决方案是

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

假设在调用此函数之前,用户会进行一些范围验证。

答案 2 :(得分:0)

我猜你试图遍历数组。你写了counter < size++,这意味着在检查size之后递增counter < size(我猜它是应该保留项目数的变量)。 ++运算符不会为您提供另一个等于size + 1的值;相反,它以size的方式递增size = size + 1。因此size会增加同一时间counter,并且索引最终将超出范围,并且在尝试写入该位置时程序将崩溃。

另外,自srand起,您只需拨打一次(例如在您的main()中)。

相关问题