2016-09-25 77 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; 
}