James Aguilar wrote:
If you change your functions to look like
---- CODE ----
void t1(double **a, int y, int x);
int main() {
double d[5][5];
d[2][2] = 2.3;
t1(d, 5, 5);
}
void t1(double **a, int y, int x) {
for(int i=0;i<y;i++)
for (int j=0;j<x;j++)
cout << "a["<<i<<"]["<<j<<"]: "<<a[i][j]<<endl;
}
---- /CODE ----
it would work better.
Not really :-)
The reason is that the memory layouts of [][] and ** are different.
if you declare
double d[2][3];
then 'd' looks in memory like this:
d
+---+---+---+---+---+---+
| | | | | | |
+---+---+---+---+---+---+
| | |
+---- 3 ----+---- 3 ----+
| |
+---- 2 ----+
That's: a piece of memory which gets divided by the compiler into 2 subarrays
of size 3 each. The 2D structure exists only for the compiler and is used for
address calculation of a single element only.
while in t1 you did:
double ** a
which has a memory layout of (again with numbers 2 and 3)
a
+----+ +---+---+---+
| o------->| | | |
+----+ +---+---+---+ +---+---+---+
| o----------------------->| | | |
+----+ +---+---+---+
That is: an array of 2 pointers pointing to arrays of size 3.
As you can see, those structures are completely different.
*But*: The syntax to access a single element is identical in both
cases. Exercise for the reader: Why is this so? Why can
d[1][1] be written as well as a[1][1] and do both expressions
produce the same machine code?
--
Karl Heinz Buchegger
kb******@gascad.at