int*p[ ]与int(*p)[ ]的区别
举例说明:
1)int* p[2] 是一个指向int型的指针数组,即:p是包含两个元素的指针数组,指针指向的是int型。
可以这样来用:
1 #include <iostream> 2 3 using namespace std; 4 5 int main(int argc, char* argv[]) 6 7 { 8 9 int* p[2]; 10 11 int a[3] = {1, 2, 3}; 12 13 int b[4] = {4, 5, 6, 7}; 14 15 p[0] = a; 16 17 p[1] = b; 18 19 int i; 20 cout << "output the first:" <<endl; 21 for(i = 0; i < 3; i++){ 22 23 cout << *p[0] + i << endl;// cout << **p + i; 24 cout << **p + i << endl; 25 cout << "*p:" << *p << endl; 26 cout << "&*p" << &*p << endl; 27 cout << "p:" << p << endl; 28 cout << "&p:" << &p << endl; 29 } 30 31 cout << "output the second:" <<endl; 32 33 for(i = 0; i < 4; i++){ 34 35 cout << *p[1] + i << endl;//not equal cout << **p + i; 36 37 cout << p << endl;//the same af 38 39 cout << &p << endl;//the same bf 40 } 41 return 0; 42 43 }
(2)对于 int (*p)[2], 它相当于一个二维数组的用法,只是它是一个n行2列的数组,可以这样来用:
1 #include <iostream> 2 using namespace std; 3 4 int main() { 5 int (*p)[2]; 6 int b[3][2] = {{1, 2}, {3, 4}, {5, 6}}; 7 8 p = b; 9 10 for(int i = 0; i < 3; i++) { 11 for(int j = 0; j < 2; j++){ 12 //the flowings equal to each other 13 cout << p[i][j] << endl; 14 cout << *(*(p+i)+j) << endl; 15 } 16 } 17 return 0; 18 }
注意:
(1)为行数确定、列数不确定,即为2*n型的。
(2)为n*2型的数组的指针用法,即行数不确定、列数确定。
对于(1)其等价形式如下:
1 #include <iostream> 2 3 using namespace std; 4 5 int main() { 6 7 int** array; 8 9 array = new int* [2]; 10 11 int a[3] = {1, 2, 3}; 12 13 int b[4] = {4, 5, 6, 7}; 14 15 array[0] = a; // *array = a; 16 17 array[1] = b; // *(array+1) = b; 18 19 for(int i = 0; i < 3; i++){ cout << array[0][i]<< endl; 20 cout << *array[0] + i << endl; 21 } 22 23 cout << endl; 24 25 for(int j = 0; j < 4; j++){ 26 cout << array[1][j] << endl; 27 cout << *array[1] + j << endl; 28 } 29 return 0; 30 }
其实以上用法即这我们常用的动态二维数组的用法