指向指針的指針的理解和應用
阿新 • • 發佈:2017-11-05
應用 ios 維數 scanf () main 泄露 argc bsp
總結:
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
指向指針的指針的理解和應用