Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 726
Nathalie B Avatar asked Apr 21 '11 15:04

Nathalie B


People also ask

How do you allocate the size of an array?

To allocate memory for an array, just multiply the size of each array element by the array dimension. For example: pw = malloc(10 * sizeof(widget));

How do I allocate a large array in C++?

Allocate an array with code>newint* a = NULL; // Pointer to int, initialize to nothing. int n; // Size needed for array cin >> n; // Read in the size a = new int[n]; // Allocate n ints and save ptr in a.

How are arrays allocated in memory?

Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.

Can we increase the size of array using malloc?

In this tutorial, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(), calloc(), free() and realloc(). As you know, an array is a collection of a fixed number of values. Once the size of an array is declared, you cannot change it.


1 Answers

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.

like image 69
MByD Avatar answered Sep 28 '22 04:09

MByD