我有一个非常简单的 for 循环来生成一些随机 float :
int dim = 6;
int n = 100000;
int size = n * dim;
float data[size],r;
for(int i = 0; i < size; i++)
{
r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
data[i] = r;
}
它工作正常,直到我将 n 的大小从 100000 增加到 1000000。这是 ideone 上的完整代码:http://ideone.com/bhOwVr
实际上在我的电脑上它只适用于 n=10000。任何更大的数字都会导致崩溃。没有错误信息。
最佳答案
如果您声明一个固定大小的数组,它将分配在堆栈上。该程序的堆栈内存非常有限。 Here are some examples for default values .还有相关阅读:What and where are the stack and heap?
您可以增加堆栈大小...不推荐但有效:
[luk32@localhost tests]$ g++ ./stack_mem.c
[luk32@localhost tests]$ ./a.out
Segmentation fault (core dumped)
[luk32@localhost tests]$ ulimit -s 32768
[luk32@localhost tests]$ ./a.out
[luk32@localhost tests]$ #it worked.
或者在堆上动态分配内存:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand ( time(NULL) );
int dim = 6;
int n = 1000000;
int size = n * dim;
float *data,r;
data = new float[size];
for(int i = 0; i < size; i++)
{
r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
data[i] = r;
}
delete[] data;
return 0;
}
结果:
[luk32@localhost tests]$ g++ ./stack_mem.c
[luk32@localhost tests]$ ./a.out
[luk32@localhost tests]$
虽然,毕竟我会推荐使用 c++ 功能,例如 vector
和 randoms
.
关于c++ - 在for循环中生成随机 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782996/