如何将随机整数分配给C++中的长整型动态数组?

huangapple go评论54阅读模式
英文:

How to assign random int to long int dynamic array in C++?

问题

为了创建一个用随机数填充动态分配数组的方法,我使用了以下方法:

void autoFill(long int *fillArr[], int length) {
srand(1024);
for (int i = 0; i < length; i++) {
fillArr[i] = rand();
}
}

然而,`fillArr[i] = rand();` 不起作用,因为这行试图将 `int` 转换为 `long *`。您应该如何赋值呢?

<details>
<summary>英文:</summary>

To make a method for filling dynamically assigned array with random numbers, I used following method:

void autoFill(long int *fillArr[], int length) {
srand(1024);
for (int i = 0; i < length; i++) {
fillArr[i] = rand();
}
}

However, `fillArr[i] = rand();` doesn&#39;t work because this line tries to convert `int` to `long *`. How do I assign this?

</details>


# 答案1
**得分**: 0

I assume you have an 1D array that stores long int, you pass the argument in the wrong way
```cpp
#include <iostream>
#include <stdlib.h> 
#include <ctime>

void auto_fill(long int *arr, int length) {
    srand(1024);
    for (int i = 0; i < length; i++) {
        arr[i] = rand();
    }
}

int main()
{
    long int *myarray;
    int length = 20;
    myarray = new long int[length];
    auto_fill(myarray, length);
    for (int i = 0; i < length; i++)
        std::cout << myarray[i] << std::endl;
}

please note that rand() returns an int, not a long int

英文:

I assume you have an 1D array that stores long int, you pass the argument in the wrong way

#include &lt;iostream&gt;
#include &lt;stdlib.h&gt; 
#include &lt;ctime&gt;

void auto_fill(long int *arr, int length) {
	srand(1024);
	for (int i = 0; i &lt; length; i++) {
		arr [i]=rand();
	}
}

int main()
{
	long int *myarray;
	int length=20;
	myarray = new long int[length];
	auto_fill(myarray, length);
	for (int i=0;i&lt;length;i++)
		std::cout &lt;&lt; myarray [i]&lt;&lt;std::endl;
}

please note that rand() return a int, not a long int

答案2

得分: -3

看起来我不得不写*(fillArr[i]) = rand();而不是fillArr[i] = rand();现在又出现了另一个问题。

英文:

Looks like I had to write *(fillArr[i]) = rand(); instead of fillArr[i] = rand();
Now there is another problem, though.

huangapple
  • 本文由 发表于 2023年5月25日 01:39:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定