[英]how to allocate large arrayes using C in linux
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.