Reputation: 211
I came across this bit of code (source):
// memory allocation
float *temp = new float[(order-1)*(order-1)];
float **minor = new float*[order-1];
for(int i=0;i<order-1;i++)
minor[i] = temp+(i*(order-1));
and I really don't understand it. What is the author of this code trying to accomplish? (Yes I know he's trying to make a program to find the inverse of a matrix, but I don't see how this bit of code works.)
I would think this is equivalent:
float **minor;
minor = new float*[order-1];
for(int i=0;i<order-1;i++)
minor[i] = new float[(order-1)*(order-1)];
because the +(i*(order-1))
seems like it's only there to move forward what is essentially the width of a memory cell. I'm sure that I couldn't be more wrong with this hypothesis, though. Despite my wrong theory, I can't find an explanation for this anywhere, so an in-depth explanation would be much appreciated. Explaining how one would implement this with a vector of vectors of floats might also be helpful.
Upvotes: 1
Views: 35
Reputation: 2430
The first code is effectively allocating an (order-1) x (order-1) matrix. It can be addressed like minor[i][j]. It can also be addressed linearly through temp: temp[i * (order-1) + j]. Sometimes having these two ways to address a matrix can be convenient. Many commercial/open source matrix libraries work with linearly addressed matrices.
Another way to look at it: temp is being allocated as a big block and then minor is indexing into temp for each row (or column, depending on your point of view).
The second code is not the same. It is allocating (order-1)x(order-1)x(order-1) elements.
Upvotes: 1