二级指针早在学校的时候就学习过并且略加研究过,但总觉得就是自己理解的那么一回事吧,而且感觉也确实不是一定要用它。但是今天在研究平衡二叉树的时候发现别人写的代码里面用到了二级指针,自己感觉不是很理解,认为这用一级指针也可以解决啊,事实是不是这样呢?未必,先看一道面试题:
题目是这样的:
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
//p = new char[num]; //C++当中
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = NULL;
GetMeory(str, 100);
strcpy(str,"Hello");
cout << str << endl;
return 0;
}
问:程序能否达到目的:在GetMemory()中为main函数中的开辟空间,并将str指向这段空间?
这道题目一看就知道问题出就出在使用了一级指针上了,所以需要用二级指针:
正确的方法应该采用二级指针,程序如下:
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
void GetMeory(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
//*p = new char[num]; //C++当中
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = NULL;
GetMeory(&str, 100);
strcpy(str,"Hello");
cout << str << endl;
return 0;
}
这时候看到二级指针的用处了吧?或者上面的面试题用一级指针也行,将函数的返回值改成返回一个指针变量即可。
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
char * GetMeory2(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
//p = new char[num]; //C++当中
return p;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = NULL;
str = GetMeory2(str, 100);
strcpy(str,"Hello");
cout << str << endl;
return 0;
}
另外用二级指针还经常用在动态申请二维数组。
代码如下:
void main()
{
int m , n , **p;
scanf("%d%d" , &m , &n);
p = (int **)malloc(m * sizeof(int *))
//C++中建议使用:p = new int* [m];
for(i = 0 ; i < m ; i++)
p[i] = (int *)malloc(n * sizeof(int));
//C++:p[i] = new int[n];
}
这样就实现了二维数组的动态申请,因为一般数组声明时,不允许下标是变量,所以如果想动态决定数组各维的大小,最好这样做。