静态矩阵转换为指针

时间:2012-01-11 22:17:15

标签: c++ matrix

我有矩阵M:

float M[4][3] = {
    0, 0, 0,
    0, 1, 1,
    1, 0, 1,
    1, 1, 0};

我需要使用方法“foo”来投射M:

foo(float **matrix){ 
    printf("%f",matrix[0][0]);
}

我使用以下代码成功编译了代码:

foo( (float**) M )

但是当我执行它时,我遇到了段故障。怎么了?我在Ubuntu Oneiric中使用g ++。

提前致谢。


好的,谢谢Luchian,但是如何使用:

float **M = new float*[4];
M[0] = {0,0,0};

我知道它不能编译,但它有类似的东西吗?

2 个答案:

答案 0 :(得分:0)

如果你想(或需要)自己做arith,请避免演员:

void foo(float **pmatrix)
{
    float *matrix = *pmatrix;

    for (int r = 0; r < 4; ++r)
    {
        for (int c = 0; c < 3; ++c)
            printf("%f ", matrix[(r * 3) + c]);
        printf("\n");
    }
}

float M[4][3] = {
    0, 0, 0,
    0, 1, 1,
    1, 0, 1,
    1, 1, 0
};

int main()
{
    float *p = &M[0][0];
    foo(&p);
}

但是这段代码很丑陋且容易出错,如果可能的话,请遵循Luchian的建议并更正声明。

答案 1 :(得分:0)

好的,最好的:

float **M = new float*[4];
for(int i=0; i<4; i++){
    M[i] = new float[3];
    for(int j=0; j<3; j++){
        M[i][j] = something...
    }
}