2016-09-25 73 views
-5

我想將我的大二維數組初始化爲零。 如果我通過calloc分配內存,它會自動初始化所​​有單元爲零。 是否可以使用單個calloc函數爲二維數組分配內存? 謝謝使用calloc分配內存

+6

是的,這是可能的,你的問題是非常不清楚的。你問來幹什麼?你爲什麼試試這種方式無效? –

+0

是否可以一氣呵成,可能取決於你所說的2D數組。請給出一個你想要做什麼的例子。 – Evert

+0

如何初始化我的大2d數組爲零? (數組大小可能爲10^12) –

回答

-3
int nrows = 2000, ncolumns = 190; 

int **a=calloc(nrows * ncolumns, sizeof(a)); 

printf("%d", a[0][0]); 
1

如果您希望能夠通過使用[]運營商來訪問矩陣的元素,你必須首先分配包含指向存儲在矩陣中的每一行數據的中間結構。

每一行都將歸零,因爲它們使用calloc()進行分配。這是你在找什麼?

#include <stdlib.h> 
#include <stdio.h> 

int main(void) 
{ 
    int **a; 
    unsigned int num_rows = 2000; 
    unsigned int num_columns = 190; 

    a = calloc(num_rows, sizeof(*a)); 
    if (a == NULL) { 
     /* TODO: Error handling. */ 
     return -1; 
    } 

    for (unsigned int i = 0; i < num_rows; i++) { 
     a[i] = calloc(num_columns, sizeof(**a)); 
     if (a[i] == NULL) { 
      /* TODO: Error handling. */ 
      return -1; 
     } 
    } 

    printf("%d\n", a[0][0]); 

    /* TODO: Free calloc'd memory. */  

    return 0; 
}