In trying to understand pointers, I created a M[x][y] array, a pointer to said array *p_M[x] and a pointer to said pointer **d_p_M. The first pointer points to the first element of a row in the array M, and the double pointer points to the first row in *p_M.
Inside the function the results are as expected, but when trying to accessing the elements in main the results get funky.
Can anyone help me understand what I'm doing wrong please?
Below is the relevant code:
struct Matrix
{
int rows;
int cols;
double **pMatrix;
};
struct Matrix unity_matrix(int row, int col);
int main()
{
int row = 10, col = 10;
struct Matrix m1 = unity_matrix(row, col);
for (int x = 0; x < row; x++)
{
printf("\nOutside result %d\n", x);
for (int y = 0; y < col; y++)
{
printf("%lf ", m1.pMatrix[x][y]);
}
}
printf("\n Rows = %d Cols = %d", m1.rows, m1.cols);
return 0;
}
struct Matrix unity_matrix(int row, int col)
{
double v_mtrx[row][col], *p_v_mtrx[row];
for (int x = 0; x < row; x++)
{
for (int y = 0; y < col; y++)
{
v_mtrx[x][y] = x + y + 1.0;
}
}
for (int i = 0; i < row; i++) p_v_mtrx[i] = (double*) v_mtrx + i * col;
struct Matrix mtrx = { row, col, (double **) p_v_mtrx
};
for (int x = 0; x < row; x++)
{
printf("\nInside result %d\n", x);
for (int y = 0; y < col; y++)
{
printf("%lf ", mtrx.pMatrix[x][y]);
}
}
return mtrx;
}
Inside result 0
1.000000 2.000000 3.000000 4.000000
Inside result 1
2.000000 3.000000 4.000000 5.000000
Inside result 2
3.000000 4.000000 5.000000 6.000000
Inside result 3
4.000000 5.000000 6.000000 7.000000
Outside result 0
1.000000 2.000000 3.000000 4.000000
Outside result 1
0.000000 -14995397491898438029096961572323840644014499700292909391043299898885044272963634128744240168119533593897190786000787827379354468352.000000 4.000000 0.000000
Outside result 2
0.000000 0.000000 0.000000 0.000000
Outside result 3
0.000000 0.000000 0.000000 0.000000
static(orextern) are automatic -- almost always "on the stack" although the standard doesn't require that -- and automatic variables aren't valid after the block exits (here after the function returns). Although using more complicated types, this is the same as stackoverflow.com/questions/1224042/… from 2009 and stackoverflow.com/questions/11656532/returning-an-array-using-c from 2012.std::arrayin C++. In this caseunity_matrix()returns aMatrix, not a* Matrix, so the return isn't a pointer context. It won't work because when setting the fields ofMatrix mtrx,p_v_mtrxis a pointer to stack memory and will be freed on return.struct, which is valid. But it contains pointer to a local arrayv_mtrx, which goes out of life.