Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Float matrix passed as a parameter to a function gives garbage values

I want to pass a float matrix to another function from the main function, the code being as follows:

#include <stdio.h>
 
// n must be passed before the 2D array
void print(int m, int n, float arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    float arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
}

This gives the output:
3 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874

I tried this by replacing float by int for the type of the array and it works perfectly fine. I expected it would work the same way with float, outputting "1 2 3 4 5 6 7 8 9" but instead it outputs garbage values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

%d is the wrong format for floats. Using %f should solve the issue, and you should see the expected results. If you want to print only the "whole" part of the float, you can specify the precision too:

printf("%.0f ", arr[i][j]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading