Static Matrix Casting to a pointer

后端 未结 2 1486
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-01-27 01:47

    Ok, the old best:

    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...
        }
    }
    
    0 讨论(0)
提交回复
热议问题