小编Phi*_*p-P的帖子

将C代码移植到C ++,将void *从malloc转换为所需指针的问题

我目前正在移植一些我写给C ++的C代码以供娱乐。我有挣扎malloc()呼叫我在做C,与hw是为简单起见常数,但后来随着运行时间的常数交换:

double (*g2)[h][w] = malloc(h * w * sizeof(double));
Run Code Online (Sandbox Code Playgroud)

在C语言中,这是A的隐式转换void*,而C ++当然不会实现。

我已经尝试使用进行强制转换reinterpret_cast<double[h][w]>,但这仍然是无效的强制转换。

我想知道如何才能用C ++进行这项工作,因为这可以节省很多工作?

作为替代,我可能会使用带间接的矩阵类:

struct Matrix : std::vector<double> {
    unsigned matSize;
    std::vector<double*> indirection;
    Matrix() : matSize(0) {}
    Matrix(unsigned n) : matSize(n) {
        resize(n*n);
        indirection.resize(n);
        for(unsigned i = 0; i < n; ++i) {
            indirection[i] = &(*this)[i*n];
        }
    }
    double& operator()(unsigned i, unsigned j) {
        return indirection[i][j];
    }
    const double& operator()(unsigned i, unsigned j) const {
        return indirection[i][j];
    } …
Run Code Online (Sandbox Code Playgroud)

c++ pointers type-conversion void-pointers

4
推荐指数
1
解决办法
231
查看次数

标签 统计

c++ ×1

pointers ×1

type-conversion ×1

void-pointers ×1