谁能解释为什么在C ++中声明动态2D数组时为什么使用指针(**)?我不明白为什么要为此使用循环。
using namespace std;
int main(){
int **matrixPtr;//2d array declaretion
cout << "enter no of rows: ";
int row;//defining row
cin >> row;//initializing value of row from user
cout << "enter no of columns : ";
int col;//defining column
cin >> col;//initializing value of column from users
matrixPtr = new int *[row];//allocating 2d array dynamically
for(int i=0;i<row;i++){
matrixPtr[i] = new int[col];
}
}
大约2D矩阵只是1D矩阵,其元素是基本元素的1D矩阵,因此是数组的数组。对?
然后,如果要动态分配它,则可以:
int
,int *
是指向int的指针;有多少,说cols
,int **
,指向int的指针,有多少个,说rows
。然后,您需要在(3)处循环,因为您需要独立分配每个大小为1D的数组cols
...您有rows
每个大小为1的行cols
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句