二维数组与二级指针
- 二维数组在内存中以一维数组的方式排布
- int m[2][3] m的类型为int(*)[3]
- c语言中数组参数会退化为指针
数组参数 – 等效的指针参数
float a[5] – float* a
int* a[5] — int** a
char a[3][5] — char (*a)[5]
- 多维数组参数必须提供除第一维之外的所有维长度,
对于多维数组的函数参数只有第一维是可变的
动态地申请二维数组
#include <stdio.h>
#include <malloc.h>
int** malloc2d(int row, int col)
{
int** ret = NULL;
if( (row > 0) && (col > 0) )
{
int* p = NULL;
ret = (int**)malloc(row * sizeof(int*));
p = (int*)malloc(row * col * sizeof(int));
if( (ret != NULL) && (p != NULL) )
{
int i = 0;
for(i=0; i<row; i++)
{
ret[i] = p + i * col;
}
}
else
{
free(ret);
free(p);
ret = NULL;
}
}
return ret;
}
void free2d(int** p)
{
if( *p != NULL )
{
free(*p);
}
free(p);
}
int main()
{
int** a = malloc2d(3, 3);
int i = 0;
int j = 0;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d, ", a[i][j]);
}
printf("\n");
}
free2d(a);
return 0;
}