总结:

1. 申请内存,此处GetMeory参数不用指向指针的指针将无法得到内存,多次调用还会造成内存泄露。  

当然此处的GetMeory可以用返回指针的方式,这样就可以不用指向指针的指针。

#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;
}

2. 二级指针还经常用在动态申请二维数组

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]; 

  // 释放
  for(i=0; i<m; i++)
  free(p[i]);
  delete [] p[i]; // C++ [] 不可少
  free(p);
  delete [] p;
}

    

 

参考:

http://www.jb51.net/article/37516.htm

http://blog.csdn.net/bzhxuexi/article/details/17230073

posted on 2017-11-05 16:19  swing07  阅读(443)  评论(0编辑  收藏  举报