代码:
#include <iostream>
using namespace std;
int main(void)
{
int m, n;
int i, j;
int **p;
cout<<"please input the row and col:"<<endl;
cin >> m >> n;
//scanf("%d%d", &m, &n);
p = (int**)malloc(sizeof(int*)*m); //开辟行
for (i = 0; i < m; i++)
cout << "p"<<i<<" address is "<<p + i << endl;
for (i = 0; i < m; i++)
{
*(p + i) = (int*)malloc(sizeof(int)*n);//开辟列
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cout << &p[i][j]<<" ";
}
cout << endl;
}
//释放开辟的二维空间
for (i = 0; i < m; i++)
{
free(*(p + i));
}
system("pause");
return 0;
}
结果:
解析:
p = (int**)malloc(sizeof(int*)*m); //开辟行
这一句的时候,p0, p1, p2 本身并不是每行的首地址,p0, p1, p2中存放的内容为每行首地址, 而且行与行之间的地址并不一定连续。