Trying to understand pointers, basically 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 point 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 %dn", 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 %dn", 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
pasty guacamole is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.