分配一个大 (5000+) 数组 [英] Allocating A Large (5000+) Array
问题描述
我正在开发一个应用程序,输入的数据有三种可能的大小:
I am working on an application were there are three possible sizes for the data entered:
- 小:1000 个元素
- 中 = 5000 个元素
- 大= 500,000 个元素
问题是我无法分配大数组.似乎不接受大于 5000 的大小.
The problem is that I can't allocate the large array. It seems that a size larger than 5000 is not accepted.
执行以下操作时出现运行时错误:
I get a run time error when I do the following:
long size=1000;
char ch;
int arr[size];
ch=getch();
if(ch==..)
size=...;
1000 和 5000 的大小似乎工作正常,但如何以这种方式制作大小为 500k 的数组?
Sizes of 1000 and 5000 seem to work fine, but how can I make an array of size 500k in this way?
推荐答案
可以在堆上分配这么大的数组:
You can allocate such a big array on the heap:
int *arr;
arr = malloc (sizeof(int) * 500000);
不要忘记检查分配是否成功(如果不是 - malloc 返回 NULL).
Don't forget to check that allocation succeded (if not - malloc returns NULL).
正如 pmg 所提到的 - 因为这个数组不在堆栈中,所以一旦你完成了它,你必须释放
它.
And as pmg mentioned - since this array is not located in the stack, you have to free
it once you finished working with it.
这篇关于分配一个大 (5000+) 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!