70,021
社区成员




//申请二维动态数组
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int DataType;
//二维数组申请函数
int **ApplyTwo( int row, int col)
{
DataType **array;
int i;
if ((array=(DataType**)malloc(row*sizeof(DataType*)))==NULL) //分配行的空间
{
printf("0error");
exit(0);
}
for ( i = 0; i < row; i++) //在每一行分配列的空间
{
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);
{
printf("1error");
getchar();
exit(0);
}
}
return array;
}
//销毁内存空间
DestroyMem(DataType **array,int row)
{
int i;
for ( i = 0; i < row; i++)
{
free(array[i]); //先逐个释放行的内存。
}
free(array); //在释放指向一维数组的内存。
}
//主函数
int main()
{
DataType **s;
int i,j,c=1;
int row = 3, col = 5;
s=ApplyTwo(row, col);
for ( i = 0; i < row; i++)
{
for ( j = 0; j < col; j++)
{
s[i][j] = c;
c++;
}
}
for ( i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d ", s[i][j]);
}
printf("\n");
}
DestroyMem(s, row);
system("pause");
return 0;
}
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL)