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-


分享到:


相關文章: