"imspossible" error on a simplest code [closed]

You have to return from this function a pointer to pointer to float. But you return now just first value.

float** createMatrix( int N )
{
    int i,j;
    float **matrix;
    matrix = new float*[N];
        if (matrix == NULL)
        {
            free(matrix);
            return 0;
        }
    for (i=0; i<N; i++)
        matrix[i] = new float[N];
    for(i=0; i<N;i++)
        for(j=0; j<N;j++)
            matrix[i][j] = rand() % 5; // not just rand(), in this case you become numbers in range [0, max int)
    return matrix;
}

And then by storing your matrix too. A pointer should be stored, not the first value.

float **m = createMatrix(N);

Next line will give you always 1. It is because matrix is a pointer and all pointers have size 4 bytes. So you have 4 / 8 == 1.

int N = sizeof(matrix)/sizeof(float);

In case with raw dyn arrays we need to pass the size as a parameter.

void printMatrix(float **matrix, int N) { /* do work */ }

Finally you call this function so.

printMatrix(m, N);

But in C++ you should use std and dont care about all these pointers, that look actually terrible. std::vector does that work for us.

EDIT 1:
As was corrected in comments, not all pointers have 4 bytes size. At 64-bit systems it haves 8.

EDIT 2:
We should not forget to free memory:

for (int i = 0; i < N; ++i) {
    delete m[i];
}
delete[] m;

Leave a Comment