Nathalie B
Nathalie B

Reputation: 101

Allocating A Large (5000+) Array

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

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?

Upvotes: 8

Views: 23704

Answers (3)

Pepe
Pepe

Reputation: 6480

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);

Upvotes: 9

MByD
MByD

Reputation: 137282

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.

Upvotes: 10

David Heffernan
David Heffernan

Reputation: 612874

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

Upvotes: 4

Related Questions