Static Matrix Casting to a pointer

后端 未结 2 1487
攒了一身酷
攒了一身酷 2021-01-27 01:00

I have matrix M:

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

And I need to cast M with the purpose of use the method

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 01:42

    If you want (or need) to do the arith yourself, avoid the cast:

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

    But this code is ugly and error prone, if possible follow Luchian advice and correct the declaration.

提交回复
热议问题