c++11 - Can Someone explain this C++ code to me? -
its exemple of 2d pointers in 1 of slides teacher gave us. can't seem understand code other pointer pointer.
ps: still beginner @ c++
#include <iostream> using namespace std; int **ptr; int main(){ ptr=new int *[3]; (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; }
taking account comments i'll try explain unclear.
let's assume there 3 integers
int x = 1; int y = 2; int z = 3;
and going declare array of pointers these integers. declaration like
int * a[3] = { &x, &y, &z };
or
int * a[3]; *( + 0 ) = &x; // same a[0] = &x; *( + 1 ) = &y; // same a[1] = &y; *( + 2 ) = &z; // same a[2] = &z;
take account array designator used in expressions rare exceptions converted pointer first element.
so example in expression
*( + 1 )
the array designator a
converted pointer of type int **
.
now if want same allocating array dynamically can write
int **ptr = new int *[3] { &x, &y, &z };
or
int **ptr = new int *[3]; *( ptr + 0 ) = &x; // same ptr[0] = &x; *( ptr + 1 ) = &y; // same ptr[1] = &y; *( ptr + 2 ) = &z; // same ptr[2] = &z;
as type of pointer ptr
int **
example expression ptr[0]
has type int *
, can store address of variable x
in expression.
the expression ptr[0]
having type int *
equivalent expression *( ptr + 0 )
or *ptr
.
Comments
Post a Comment