C|三種方法創建二維動態數組

相對來說,創建二維動態數組比一維動態數組更復雜些,可以分別在以下三種情況下創建二維動態數組:已知一維、已知二維、或兩者都未知:

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

const int rows=3;
const int Cols=4;

void arr2D(int** arr,int rows,int cols)
{
\tint i,j;
\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tarr[i][j]=i*cols+j+1;
\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tprintf("%4d",arr[i][j]);
\tprintf("\\n");
}

int main()
{
\tint i,j;
// 1 利用指針數組生成一個rows*cols的動態二維數組,但第一維rows是固定的一個常量
\tint* p[rows]; // const int rows=3;
\tint cols;
\tprintf("請輸入二維數組的列數(默認%d行):",rows);
\tscanf("%d",&cols);
\tfor(i=0;i<rows>\t{
\t\tp[i]=(int*)malloc(sizeof(int)*cols);
\t\tif(p[i]==NULL)
\t\t\texit(1);
\t}
\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tp[i][j]=i*cols+j+1;
\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tprintf("%4d",p[i][j]);
\tprintf("\\n");
\tfor(i=rows-1;i>=0;i--) // 釋放
\t\tfree(p[i]);

// 2 利用二維指針,生成一個rs*cs的二維動態數組
\tint** pp;
\tint rs,cs;
\tprintf("請輸入二維數組的行數和列數(間隔空格):");\t
\tscanf("%d %d",&rs,&cs);
\tpp=(int **)malloc(sizeof(int *) * rs);
\tif(pp==NULL)
\t{

\t\tprintf("pp is null");
\t\texit(1);
\t}
\tfor(i=0;i\t{
\t\tpp[i]=(int*)malloc(sizeof(int)*cs);
\t\tif(pp[i]==NULL)
\t\t\texit(1);
\t}
\tarr2D(pp,rs,cs);
\tfor(i=rs-1;i>=0;i--)
\t\tfree(pp[i]);
\tfree(pp);

// 3 利用數組指針(行指針)生成一個Rows*Cols的動態二維數組,但第二維Cols是固定的一個常量
\tint (*parr)[Cols]; // const int Cols=4;
\tint Rows;
\tprintf("請輸入二維數組的行數(默認%d列):",Cols);
\tscanf("%d",&Rows);
\tparr=(int(*)[Cols])malloc(sizeof(int)*Rows*Cols);
\tif(parr==NULL)
\t\texit(1);

\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tp[i][j]=i*Cols+j+1;
\tfor(i=0;i<rows>\t\tfor(j=0;j<cols>\t\t\tprintf("%4d",p[i][j]);
\tprintf("\\n");
\tfree(parr);

getchar();getchar();
\treturn 0;
}
/*output:
請輸入二維數組的列數(默認3行):4
1 2 3 4 5 6 7 8 9 10 11 12
請輸入二維數組的行數和列數(間隔空格):3 4
1 2 3 4 5 6 7 8 9 10 11 12
請輸入二維數組的行數(默認4列):3
1 2 3 4 5 6 7 8 9 10 11 12
*//<cols>/<rows>/<cols>/<rows>
/<cols>/<rows>/<cols>/<rows>/<rows>/<cols>/<rows>/<cols>/<rows>/<stdlib.h>/<stdio.h>/<code>

-End-


分享到:


相關文章: