有人可以向我解释这个C ++代码吗?

时间:2017-09-13 23:57:16

标签: c++ c++11 pointers dynamic-memory-allocation

它是老师给我们的一张幻灯片中的2d指针的例子。 我似乎无法理解代码实际上是什么,然后指向指针。

PS:仍然是C ++的初学者

#include <iostream>
using namespace std;

int **ptr;
int main(){
    ptr=new int *[3];
    for (int i=0;i<3;i++){
        *(ptr+i)=new int[4];
    }
   for(int i=0;i<3;i++)
       for(int j=0;j<4;j++){
           *(*(ptr+i)+j)=i+j;
           cout<<ptr[i][j];
           cout<<"\n";
       }
return 0;

}

1 个答案:

答案 0 :(得分:0)

考虑到这些评论,我会试着解释一下不清楚的地方。

我们假设有三个整数

int x = 1;
int y = 2;
int z = 3;

我们将声明一个指向这些整数的指针数组。声明看起来像

int * a[3] = { &x, &y, &z };

int * a[3];

*( a + 0 ) = &x; // the same as a[0] = &x;
*( a + 1 ) = &y; // the same as a[1] = &y;
*( a + 2 ) = &z; // the same as a[2] = &z;

考虑到在具有罕见异常的表达式中使用的数组指示符将转换为指向其第一个元素的指针。

例如在表达式

*( a + 1 )

数组指示符a将转换为int **类型的指针。

现在,如果我们想要做同样但动态分配数组,那么我们可以编写

int **ptr = new int *[3] { &x, &y, &z };

int **ptr = new int *[3];

*( ptr + 0 ) = &x; // the same as ptr[0] = &x;
*( ptr + 1 ) = &y; // the same as ptr[1] = &y;
*( ptr + 2 ) = &z; // the same as ptr[2] = &z;

由于指针ptr的类型为int **,因此表达式ptr[0]的类型为int *,我们可以存储变量{{1}的地址在这个表达式中。

具有x类型的表达式ptr[0]等同于表达式int *或仅*( ptr + 0 )

相关问题