Is there a way to allocate an array with this size:
unsigned long M[2000][900000] ;
This is what I get when I run the program (no errors during compilation).
Processus arrêté (Process stopped)
Is there a way to allocate an array with this size:
unsigned long M[2000][900000] ;
This is what I get when I run the program (no errors during compilation).
Processus arrêté (Process stopped)
unsigned long (*pM)[2000][900000] = malloc(sizeof *pM);
does the job.
Use it like this
#define ROWS_MAX (2000)
#define COLUMNS_MAX (900000)
...
unsigned long (*pM)[ROWS_MAX][COLUMNS_MAX] = malloc(sizeof *pM);
/* 1st test whether the allocation succeeded! */
if (NULL == pM)
{
perror("malloc() failed");
exit(EXIT_FAILURE);
}
/* Then initialise the array. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
for (size_t column = 0; column < COLUMNS_MAX; ++column)
{
(*pM)[row][column] = 42;
}
}
/* Do something ... */
...
/* Deallocate, free the memory. */
free(pM);
An alternative approach using more than one block or memory would be using a scattered/sparse array:
unsigned long ** ppM = malloc(ROWS_MAX * sizeof *ppM);
if (NULL == ppM)
{
perror("malloc() for row pointers failed");
exit(EXIT_FAILURE);
}
for (size_t row = 0; row < ROWS_MAX; ++row)
{
ppM[row] = malloc(COLUMNS_MAX * sizeof *ppM[row]);
if (NULL == ppM[row])
{
perror("malloc() for a column failed");
exit(EXIT_FAILURE);
/* If not exiting the process here (but probably return from the function
we are in), we need to perform a clean-up on what had been allocated
so far. See below code for free()ing it as a hint how to approach this. */
}
}
/* Then initialise the array. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
for (size_t column = 0; column < COLUMNS_MAX; ++column)
{
ppM[row][column] = 42; /* Note the difference how to access the array. */
}
}
/* Do something ... */
...
/* Deallocate, free the memory. */
/* Free columns. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
free(ppM[row]);
}
/* Free row pointers. */
free(ppM);