user14492
user14492

Reputation: 2234

Pass fixed sized array to a function with pointer argument

I'm wondering is there a way to get the following code to work, or do I have to create a new copy of the function for fixed sizes? If so how can I have a generic function for fixed sizes.

void prettyPrintMatrix_float(float **matrix, int rows, int cols){
    int i, j;

    for (i = 0; i<rows; i++){
        for (j = 0; j<cols; j++){
            printf("%10.3f", matrix[i][j]);
        }
        printf("\n");
    }
    return;
}

float ppArray[4][10] = {0.0f};
prettyPrintMatrix_float(ppArray, 4, 10);

Gives an error Access violation reading location 0xFFFFF....

Upvotes: 0

Views: 1034

Answers (3)

Anton
Anton

Reputation: 11

Just another solution with templates

template<int rows, int cols>
void prettyPrintMatrix_float(float (&matrix)[rows][cols])
{
    int i, j;
    for(i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
        {
            printf("%10.3f", matrix[i,j]);
            // Or
            //printf("%10.3f", matrix[i][j]);
        }
        printf("\n");
    }
    return;
}

Upvotes: 0

Christian Gibbons
Christian Gibbons

Reputation: 4370

If Variable Length Arrays are not available to you, and your function will be taking in matrices of varying dimensions, then you're function will have to treat it as a one-dimensional array and manually do the math for calculating where the start of each row is. Something like this:

void prettyPrintMatrix_float(float *matrix, int rows, int cols){
    int i, j;

    for (i = 0; i<rows; i++){
        for (j = 0; j<cols; j++){
            printf("%10.3f", matrix[i * sizeof(float) + j]);
        }
        printf("\n");
    }
    return;
}

float ppArray[4][10] = {0.0f};
prettyPrintMatrix_float(&ppArray[0][0], 4, 10);

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

If the compiler supports Variable Length Arrays then you can define the function like

void prettyPrintMatrix_float( int rows, int cols, float matrix[rows][cols] ){
    int i, j;

    for (i = 0; i<rows; i++){
        for (j = 0; j<cols; j++){
            printf("%10.3f", matrix[i][j]);
        }
        printf("\n");
    }
}

Otherwise you can define the function like

void prettyPrintMatrix_float(const float *matrix, int rows, int cols)
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            printf("%10.3f", matrix[i * cols + j]);
        }
        putchar('\n');
    }
}

and call it like

prettyPrintMatrix_float( ( const float * )ppArray, 4, 10);

Upvotes: 2

Related Questions