FELIPE_RIBAS
FELIPE_RIBAS

Reputation: 411

Table of pointers to tables?

I'm trying to build a table of references from other tables as following:

//*** TABLE 1 ***
double ref_table1[2][3] = {{10, 5.100, 0},
                          {21, 17.620, 26}
}; 

double fit_table1[5][2] = {{0.020, 23},
                    {-0.450, 1},
                    {0.060, 2},
                    {0.098, 5},
                    {0.410, 1}
};

//*** TABLE 2 ***

double ref_table2[2][3] = {{10, 5.100, 0},
                          {21, 17.620, 26}
}; 

double fit_table2[5][2] = {{0.020, 23},
                    {-0.450, 1},
                    {0.060, 2},
                    {0.098, 5},
                    {0.410, 1}
};

(tables are equal here to simplify the example but they are of course different)

And then the place where I'm trying to make the references but keep getting error:

static double **tables[][2] = {{ref_table1, fit_table1},
                               {ref_table2, fit_table2}
};

then I took a read at this topic:

Create a pointer to two-dimensional array

and tried with:

static double (*tables)[][2] = {{ref_table1[0], fit_table1[0]},
                              {ref_table2[0], fit_table2[0]}
};

but still in this case i can't figure it out, how to do it correctly. I'm also wondering if that's actually possible since the ref_tables and fit_tables have different dimensions. I just thought it could be possible since they are all in the end references to 'double'. Any tips?

Thanks

Upvotes: 1

Views: 1061

Answers (1)

Ian Abbott
Ian Abbott

Reputation: 17403

The "ref" tables and "fit" tables have incompatible dimensions, so there is no "pointer to array" type that works for both. You will need to define a struct type with members of the appropriate "pointer to array" types.

struct reffit {
    double (*ref)[3];
    double (*fit)[2];
};

struct reffit tables[] = {{ref_table1, fit_table1},
                          {ref_table2, fit_table2},
                         };

You could also add additional members to the struct to hold the number of rows in each of the tables in case the number of rows can vary:

#define ARRAY_LEN(x) (sizeof (x) / sizeof *(x))

struct reffit {
    size_t nrefs;
    double (*ref)[3];
    size_t nfits;
    double (*fit)[2];
};

struct reffit tables[] = {
    {
        .nrefs = ARRAY_LEN(ref_table1), .ref = ref_table1,
        .nfits = ARRAY_LEN(fit_table1), .fit = fit_table1
    },
    {
        .nrefs = ARRAY_LEN(ref_table2), .ref = ref_table2,
        .nfits = ARRAY_LEN(fit_table2), .fit = fit_table2
    },
};

Upvotes: 1

Related Questions