Reputation: 119
I read this C++ tutorial, and in the pointers section there is a confusing example, exactly this:
double (*pVal2)[2]= new double[2][2]; //this will add 2x2 memory blocks to type double pointer
*(*(pVal2+0)+0) = 10;
*(*(pVal2+0)+1) = 10;
*(*(pVal2+0)+2) = 10;
*(*(pVal2+0)+3) = 10;
*(*(pVal2+0)+4) = 10;
*(*(pVal2+1)+0) = 10;
*(*(pVal2+1)+1) = 10;
*(*(pVal2+1)+2) = 10;
*(*(pVal2+1)+3) = 10;
*(*(pVal2+1)+4) = 10;
Is int (*pVal)[2]
an array pointer?
I do not understand why is it allocating memory for double[2][2]
but the *(*pVal2+1)+4)
goes to 4?
Upvotes: 0
Views: 43
Reputation: 302851
Using the spiral rule:
+--------+
| +---+ |
| ^ | |
double (*pVal2)[2];
^ ^ | |
| +-----+ |
+---------------+
pVal2
is a pointer to an array of 2 double
s. Or, simpler:
using T = double[2];
T *pVal2 = new T[2];
The rest of the code leads to undefined behavior as: *(p + idx)
is equivalent to p[idx]
, so *(*(pVal2+1)+4)
is equivalent to pVal2[1][4]
.But the type of pVal2[1]
is double[2]
, so there is no 5th element there...
Upvotes: 2