1. 程式人生 > >c語言中如何使用malloc()函式在堆上建立二維陣列

c語言中如何使用malloc()函式在堆上建立二維陣列

首先附程式碼:

#include <stdio.h>
#include <stdlib.h>
main()  //建立5行6列的陣列
{
int ** p, i;
p = (int **)malloc( sizeof(int*) * 5 );    //也可以為p=(int **)malloc(sizeof(int)*5);
for( i=0; i<5; i++ )
{
p[i] = (int *)malloc( sizeof(int) * 6 );
}

for(int m=0; m<5;m++)
{
for(int n=0; n<6; n++)
{
p[m][n] = 1;
}
}


for(int m=0; m<5;m++)
{
for(int n=0; n<6; n++)
{
printf("%d ", p[m][n]);
}
printf("%\n");
}
}

程式碼說明

p=(int **)malloc(sizeof(int*)*5);
分配一個數組大小為5,指向int*的陣列
p[i]=(int *)malloc(sizeof(int)*5);
在陣列p中的每個元素p[i]指向一塊記憶體為sizeof(int)*6空間的首地址。