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
with 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.
%d
is the wrong format for float
s. 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]);