1

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 "foo":

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

I compiled sucessfully the code using:

foo( (float**) M )

But when I executed it, I got a segment fault. What is wrong? I am using g++ in Ubuntu Oneiric.

Thanks in advance.


Ok, thanks Luchian, but what about using:

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

I know that it does not compile, but there it something similar?

JMFS
  • 297
  • 1
  • 4
  • 11
  • See http://stackoverflow.com/a/4810676/78845 – johnsyweb Jan 11 '12 at 22:27
  • @juanma2268: general rule-of-thumb, if you need a cast to make something compile then it is _often_ (not always!) wrong and your cast is hiding a problem. And that I think is the case here. – AAT Jan 11 '12 at 23:00

2 Answers2

0

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.

CapelliC
  • 59,646
  • 5
  • 47
  • 90
0

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...
    }
}
JMFS
  • 297
  • 1
  • 4
  • 11