I have the following structure:
struct tmatrix {
struct tmatrix_entry {
double price;
double amt;
} **entries;
double *stocks;
double *needs;
int rows;
int cols;
};
and the following functions:
void tmatrix_set_prices (struct tmatrix *tm, double *prices[]) {
for (int i = 0; i < tm->rows; ++i)
for (int j = 0; j < tm->cols; ++j)
tm->entries[i][j].price = (prices) ? prices[i][j] : 0;
}
void tmatrix_set_amts (struct tmatrix *tm, double *amts[]) {
for (int i = 0; i < tm->rows; ++i)
for (int j = 0; j < tm->cols; ++j)
tm->entries[i][j].amt = (amts) ? amts[i][j] : 0;
}
I think itβs not great to make 2 almost identical functions, so I still came to this:
do {\
for (int i = 0; i < TM->rows; ++i)\
for (int j = 0; j < TM->cols; ++j)\
TM->entries[i][j].FIELD = (ARRAY) ? ARRAY[i][j] : 0;\
} while (0)
And then:
void tmatrix_set_prices (struct tmatrix *tm, double *prices[]) {
TMATRIX_SET_2D_ARRAY(tm, price, prices);
}
void tmatrix_set_amts (struct tmatrix *tm, double *amts[]) {
TMATRIX_SET_2D_ARRAY(tm, amt, amts);
}
Is this a bad decision? I was told so. I was also told that this can be done using offsetof (), but it looks more complicated and tricky to use. Or maybe it would be better to make an entriesarray instead of a structure? What is the best way to implement such features?
c_spk source
share