2016-04-23 90 views
-4

分配用C大arrayes有沒有辦法用這個大小分配數組:如何在Linux

unsigned long M[2000][900000] ; 

這是我所得到的,當我運行的程序(編譯過程中沒有錯誤)。

enter image description here

Processus arrêté (Process stopped) 
+1

而看殼結構,他認爲他是編碼矩陣:D – WedaPashi

+4

請不要指出這個數組的大小是6.7GB。你的機器上有多少內存? –

+0

該陣列至少約7GB。你真的需要這麼大的陣列嗎?如果你有的話,你的邏輯/算法可能會遇到更深層次的問題。 – kaylum

回答

6
unsigned long (*pM)[2000][900000] = malloc(sizeof *pM); 

做這項工作。

使用方法如下

#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); 
使用多於一個塊或存儲器將是使用散射/稀疏陣列

的另一種方法:

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); 
+2

也有這樣一個'malloc()'檢查結果是不是null在我看來是強制性的。 – jdarthenay

+0

@jdarthenay:呃,夠公平的,現在這是一個更完整的例子... – alk

+0

它不起作用:malloc()失敗:無法分配內存 –