如何实现对结构的各个字段执行相同操作的函数?

我有以下结构:

struct tmatrix {
    struct tmatrix_entry {
        double price;
        double amt;
    } **entries;

    double *stocks;
    double *needs;
    int rows;
    int cols;
};

以及以下功能:

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;
}

我认为制作两个几乎相同的函数并不酷,所以到目前为止我已经达到了这个目的:

#define TMATRIX_SET_2D_ARRAY(TM, FIELD, ARRAY)\
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)

然后:

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);
}

这是一个糟糕的解决方案?我被告知过.我也被告知可以使用offsetof()来完成它,但它看起来更复杂,更难以使用.或者将条目设置为数组而不是结构可能会更好?实现这些功能的最佳方法是什么?

最佳答案 我没有测试过这个,但是如何在这些行中使用offsetof():

#include <stddef.h>

static void tmatrix_set_field(struct tmatrix *tm, double *vals[],
                              const size_t f_offset) {
    for (int i = 0; i < tm->rows; ++i)
        for (int j = 0; j < tm->cols; ++j)
            *(double *)(((char *)&tm->entries[i][j]) + f_offset) =
                 (vals) ? vals[i][j] : 0;
}

void tmatrix_set_prices (struct tmatrix *tm, double *prices[]) {
    tmatrix_set_field(tm, prices, offsetof(struct tmatrix_entry, price));
}

void tmatrix_set_amts (struct tmatrix *tm, double *amts[]) {
    tmatrix_set_field(tm, amts, offsetof(struct tmatrix_entry, amt));
}

你提到它“看起来更复杂”,但似乎可能不如宏复杂.

点赞