C++动态数组分配
在c++中時(shí)不能像java中一樣定義這樣的數(shù)組 int[] arr = new int[],如果我們要根據(jù)程序的運(yùn)行來實(shí)現(xiàn)動(dòng)態(tài)數(shù)組在c++中利用指針這個(gè)好東東。
動(dòng)態(tài)一維數(shù)組:
#include<iostream> using namespace std; int main() {int len;cin>>len;int *p=new int[len];delete[] p;p = NULL;return 0; }
動(dòng)態(tài)二維數(shù)組:
int main() {int row, col;cout << "Please enter the number for row and column: " << endl;cin >> row >>col;//為二維數(shù)組開辟空間int **p = new int*[row];for (int i = 0; i < row; i++){p[i] = new int[col];}for (int j = 0;j < row; j++){for (int k = 0; k < col; k++){p[j][k] = (j + 1) * (k + 1);cout << p[j][k] << &p[j][k];}cout<<endl;}
?????//釋放二維數(shù)組占用的空間
???? for (int m = 0; m < row; m++){delete[] p[m];}delete[] p;p = NULL;return 0; }
當(dāng)然要利用指針也可以實(shí)現(xiàn)多維數(shù)組,但是這是應(yīng)該利用STL中的vector更簡(jiǎn)單。
動(dòng)態(tài)一維數(shù)組:
#include<iostream> using namespace std; int main() {int len;cin>>len;int *p=new int[len];delete[] p;p = NULL;return 0; }
動(dòng)態(tài)二維數(shù)組:
int main() {int row, col;cout << "Please enter the number for row and column: " << endl;cin >> row >>col;//為二維數(shù)組開辟空間int **p = new int*[row];for (int i = 0; i < row; i++){p[i] = new int[col];}for (int j = 0;j < row; j++){for (int k = 0; k < col; k++){p[j][k] = (j + 1) * (k + 1);cout << p[j][k] << &p[j][k];}cout<<endl;}
?????//釋放二維數(shù)組占用的空間
???? for (int m = 0; m < row; m++){delete[] p[m];}delete[] p;p = NULL;return 0; }
當(dāng)然要利用指針也可以實(shí)現(xiàn)多維數(shù)組,但是這是應(yīng)該利用STL中的vector更簡(jiǎn)單。
轉(zhuǎn)載于:https://www.cnblogs.com/lgh1992314/archive/2012/11/18/5835305.html
總結(jié)
- 上一篇: (转)无边框窗口实现拖垃效果
- 下一篇: 浅谈 Request Response