# Thread: Creating a dynamic array of very large size

1. ## Creating a dynamic array of very large size

Hi all, not used this forum in quite a while but am a bit stuck on a programming assignment and would be grateful for a bit of help.

My assignment it to write a program that implements two kinds of sorting algorithms and test the speed of these algorithms on different length sequences. I'm all done and the program works but only for sequence lengths below a certain size. The sequence length and number of seqeunces is user defined so the array needs to be dynamic. If I go above roughly [6500][10] the program crashes.

Could someone advise me on how to initialise a large array.

Many thanks,
Will

2. Use malloc():
Code:
```int *dyn_array = malloc(sizeof(*dyn_array) * 65000);
if(!dyn_array)
{
fputs("Memory allocation failed. Run for your lives.\n", stderr);
exit(EXIT_FAILURE);
}```

3. What about the 10 for the second dimension?

What about the 10 for the second dimension?
That's a good question. I have no idea what the OP's original non-dynamic array's type was. I do know that he asked how to initialize a large array dynamically though, and that's what I gave him.

5. Thanks for the help, I thought it would involve malloc().

As Adak said, do I need to repeat for the second dimension, and also how do i go about accessing the array. I now get 97 "invalid types `int[int]' for array subscript" when trying to access the array:

int *sequence = (int *)malloc(sizeof(*seq) * 65000);

for(row=0;row<m;row++)
{
for(col=0;col<n;col++)
sequence[row][col]=rand();
}
Edit: The array is a two-dimensional array of ints

6. Code:
```int dim1 = 65000;
int dim2 = 10;
int i;

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

for(i = 0;i < dim1;++i)
array[i] = malloc(sizeof(**array) * dim2);

array[5][2] = 9;  // Accessing example```

7. A variant on itsme86's example that requires just two calls to malloc:
Code:
```int dim1 = 65000;
int dim2 = 10;
int i;

int *data = malloc(sizeof(*data) * dim1 * dim2);
int **array = malloc(sizeof(*array) * dim1);

for (i = 0; i < dim1; ++i)
array[i] = &data[i * dim2]

array[5][2] = 9;  // Accessing example

/* ... */

free(array);
free(data);```
Note that in your actual implementation you may wish to check that malloc does not return a null pointer.

8. Y'all have some entertaining ways to malloc a 2D array, for sure.

Code:
```#include <stdio.h>
#include <stdlib.h>

#define ROWS 80
#define COLS 10

void printIt(int **array1)
{
int i, j;

for (i = 0; i < ROWS; ++i) {
for (j = 0; j < COLS; ++j) {
printf(" %5d  ", array1[i][j]);
}
putchar('\n');
}
}

int main(void) {
int i, j;
int **array;

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

for (i = 0; i < ROWS; +++i)
array[i] = malloc(COLS * sizeof(int));

for (i = 0; i < ROWS; ++i) {
for (j = 0; j < COLS; ++j) {
array[i][j] = i + j;
}
}
printIt(array);

for(i=0;i<ROWS;++i) {
free(array[i]);
}
free(array);
return 0;
}```