[英]Unsigned long long int as an array index in C on a very big array
I need a very big array to represent a series of points.我需要一个非常大的数组来表示一系列点。 To be more exact I need 256 * UINT_MAX points that have x and y values between 0 and 1. What I've tried so far is this but when I try to access array[i] my program crashes.
更准确地说,我需要 256 * UINT_MAX 点,其 x 和 y 值介于 0 和 1 之间。到目前为止我尝试过的是这样,但是当我尝试访问 array[i] 时,我的程序崩溃了。 What I can use to iterate through that array and to allocate that memory?
我可以使用什么来遍历该数组并分配该 memory? Thank you!
谢谢!
unsigned long long int N = (unsigned long long int) 256 * (unsigned long long int) UINT_MAX;
float** array = (float**) malloc( N * sizeof(float*));
for(unsigned long long int i = 0; i < N; i++)
{
array[i] = (float*)malloc(2 * sizeof(float));
printf("Allocated");
array[i][0] = (float) rand() / RAND_MAX;
array[i][1] = (float) rand() / RAND_MAX;
}
Your programs crashes because you try to allocate a HUGE amount of memory you likely do not have (without checking the result of malloc
is NULL
).您的程序崩溃是因为您尝试分配大量您可能没有的memory (不检查
NULL
malloc
。 Indeed, UINT_MAX
is close to 4e9 on many mainstream system and so you try to allocate at least 8 * 256 * 4e9 = 8
TB of memory (without taking into account allocation in the loop that will be insanely slow)!实际上,在许多主流系统上,
UINT_MAX
接近 4e9,因此您尝试分配至少8 * 256 * 4e9 = 8
TB 的 memory(不考虑循环中的分配会非常慢)!
Assuming you're on a 64-bit platform, then it's likely that假设您在 64 位平台上,那么很可能
UINT_MAX == 4294967295
sizeof (float *) == 8
so you are trying to allocate 8 terabytes of memory in one chunk, which is almost certainly failing.所以你试图在一个块中分配8 TB的 memory,这几乎肯定会失败。 Check the return value of
malloc
to make sure it isn't NULL
.检查
malloc
的返回值,确保它不是NULL
。
Why do you think you need to allocate that large an array?为什么你认为你需要分配这么大的数组? What kind of data are you trying to model?
你想 model 什么样的数据?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.