英文:
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'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 <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() 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论