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?
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));
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With