Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

c - Allocating A Large (5000+) Array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...