1:二维数组为形参时常用形式:
eg:arr(int*(p)[])::实参为(arr)
arr(p[][]);
arr(*p)::为一重指针时,实参为(*arr),也就是成为一连串一维数组
2:动态开辟二维数组:
eg:形参为(in**)a,只能把二维数组看成一串一维数组
应用方式:*((int *)p+n*i+j)
开辟方法:
int **p;
p = (int **)malloc(sizeof(int*)*m);
p[i] = (int *)malloc(sizeof(int)*m);
3:样例
//如果函数参数是指针,不能用一级指针做函数参数实现申请动态内存
void getMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char)*num);
}
void main()
{
char *str = NULL;
getMemory(str, 20);
strcpy(str, "code");
cout << str;
system("pause");
}//出错
然而
//用二级指针为指针申请内存,用二级指针做函数参数可以申请成功
void getMemory1(char **p, int num)
{
*p = (char *)malloc(sizeof(char)*num);
}
void main()
{
char *str = NULL;
getMemory(&str);
strcpy(str, "code");
cout << str;
system("pause");
}
2.二级指针做函数参数简介修改变量的值
#include
using namespace std;
struct Teacher
{
char name[20];
int age;
};
int getTeacher(Teacher **p)
{
Teacher *tmp = NULL;
if (p == NULL)
{
return -1;
}
if (tmp == NULL)
{
return -2;
}
tmp->age = 23;
*p = tmp;//p是实参地址,*p间接修改实参的值
//用二级指针修改一级指针的值,用一级指针修改零级指针的值
}
void FreeTeacher(Teacher *p)
{
if (p == NULL)
{
return;
}
free(p);
}
int main()
{
Teacher *pt = NULL;
getTeacher(&pt);
cout << pt->age << endl;
FreeTeacher(pt);
system("pause");
return 0;
}