Allocating A Large (5000+) Array

喜夏-厌秋 提交于 2019-12-28 06:24:19

问题


I am working on an application were there are three possible sizes for the data entered:

  • small: 1000 elements
  • medium= 5000 elements
  • large= 500,000 elements

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=...;

Sizes of 1000 and 5000 seem to work fine, but how can I make an array of size 500k in this way?


回答1:


You can allocate such a big array on the heap:

int *arr;
arr = malloc (sizeof(int) * 500000);

Don't forget to check that allocation succeded (if not - malloc returns NULL).

And as pmg mentioned - since this array is not located in the stack, you have to free it once you finished working with it.




回答2:


Your stack can't hold that much data. You have to allocate big arrays on the heap as follows:

int *array = malloc (sizeof(int)*size);

As pmg pointed out remember to free your memory once your done.

free(array);



回答3:


It's too big for the stack. Instead you need to allocate it on the heap with malloc.



来源:https://stackoverflow.com/questions/5746377/allocating-a-large-5000-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!