I’m trying to understand some code that uses pointer arithmetic in a way I’m not used to. At one point in the code I encounter this:
complex<double> **P, *p_row, result=complex<double>(0,0);
P=new complex<double>*[n];
for(i=0;i<n;i++) P[i]=new complex<double>[n];
for(i=0,p_row=*P;i<n;i++,p_row+=n) result+=log(*(p_row+i));
If P is a matrix, this looks to me like adding the logarithms of the diagonal elements of P. But it turns out the last line above is not equivalent to
for(i=0;i<n;i++) result+=log(P[i][i]);
I’ve been searching for an explanation of what’s going on here but I can’t find it. Also, the code in question apparently gives the right result in the end (it’s part of a Monte Carlo). Any ideas?
The code you posted is wrong; it does invoke undefined behavior.
Eg. in the second iteration,
p_rowis(*P)+n.*Ppoints to an array of sizen, therefore, when the code reads*(p_row+i), it reads past the end of the array.The last line seems to assume the matrix is stored in a single continuous array (eg. row major). However, that means
Pwould be acomplex<double>*initialized byP = new complex<double>[n*n];.