Reputation: 173
I'm having a small issue with this problem and I could really use another set of eyes with this. I am basically trying to read a matrix that I input and then display the said matrix.
The program always returns a null matrix (0 on all positions). The size of the matrix (columns/rows) is good. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#define MAXN 10
void display_matrix(int n, int m, double a[MAXN][MAXN], char ch)
{
int i, j;
printf("\n MATRIX %c\n", ch);
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++) printf("%8.2lf ",a[i][j]);
printf("\n");
}
}
void read_matrix(int *n, int *m, double a[MAXN][MAXN])
{
int i,j;
printf("\nInput of size and elements of a matrix\n");
printf("\n\tNumber of rows, n=");
scanf("%d", n);
printf("\n\tNumber of columns, m=");
scanf("%d", m);
printf("\n\tThe elements of the matrix\n");
for (i = 0; i < *n; i++)
{
for(j = 0; j < *m; j++)
{
printf("a[%d,%d]=", i, j);
scanf("%lf",&a[i][j]);
}
}
printf("\n");
}
void main()
{
int n, m;
double a[MAXN][MAXN];
read_matrix(&n, &m, a);
display_matrix(n, m, a, 'X');
return 0;
}
Upvotes: 0
Views: 149
Reputation: 4752
Your code seems mostly fine (main()
should have a return type of int
, and you should always check the return value of scanf()
), except possibly for the following line:
printf("%8.2lf ",a[i][j]);
Prior to the C99 standard, the l
modifier was not defined in conjunction with the f
conversion specifier. Using the two in combination resulted in undefined behaviour. I don't know what the odds are, but it is not inconceivable that you have a pre-C99 C library that either misbehaves or implements %lf
to match something entirely different, perhaps long double
.
To print a double, you should use the %f
conversion specifier:
printf("%8.2f ",a[i][j]);
This is just clutching at straws though. It might not change anything at all for you.
The scanf()
function has different conversion specifiers for float
(%f
) and double
(%lf
), because it need to know the exact type that the corresponding pointer argument is pointing to.
But when you pass a float
to a variadic function, such as printf()
, the default argument promotions convert the float
to a double
. Hence, the printf()
function does not need a conversion specifier for float
, because there is no way to pass a float
to it. The C99 standard added the l
modifier just for symmetry with the scanf()
function.
Upvotes: 2