0

I'm trying to hand over the "test_array" to the double pointer "**values" which is a member of the "Matrix" struct.

I want to avoid using "malloc" because I want to use the code for an embedded system application. There are matrices with different sizes and I only want to use one struct. The idea behind this is to point to a static 2d array in order to have no memory conflicts.

#include <stdio.h>

struct Matrix {
    int rows;
    int columns;
    double **values;
};

static double test_array[2][3] = {{1,2,3},{4,5,6}};

int main (void)
{

    struct Matrix matrix;
    int i,j;

    matrix.rows = 2;
    matrix.columns = 3;
    matrix.values = test_array;

    for (i=0; i<matrix.rows; i++) {

        for (j=0; j<matrix.columns; j++) {
            printf("%f ", *(*(matrix.values + i) + j));
        }

        printf("\n");
    }

}

Pointing to a 1-d array is not a big deal, but how does it work for a 2-d array?

  • 2
    https://stackoverflow.com/questions/4470950/why-cant-we-use-double-pointer-to-represent-two-dimensional-arrays – M.M Jun 07 '18 at 23:24
  • Your best solution is probably to use `double *values` and indexing arithmetic – M.M Jun 07 '18 at 23:30
  • 1
    It doesn't work. It is not possible to directly access a `[M][N]` kind of 2D array through a `**` pointer. The compiler has already told you that you can't do `matrix.values = test_array;`. – AnT stands with Russia Jun 07 '18 at 23:49
  • One way to achieve that is to do it indirectly: introduce an additional intermediate pointer array as described here: https://stackoverflow.com/questions/3515045/passing-two-dimensional-array-via-pointer – AnT stands with Russia Jun 08 '18 at 00:17

1 Answers1

0

You can instead define your struct this way -

struct Matrix {
    int rows;
    int columns;
    double (*values)[];
};

and point it to the 2D array directly, below statement should work -

matrix.values = test_array;
UnClaimed
  • 5
  • 3