Reputation: 153
I'm attempting a project in C and I'm pretty confused by the results I'm getting. I've done quite a bit of research on how the arrays are handled and I feel like it should work. Below is my code:
for( i = 0; i<1000;i++)
{
for( j = 0; j<1000; j++)
{
if(j==0)
matrix[i][j] =i;
else{
double value = (i-j)/j;
printf("%s%d\n","value of i-j: ",value);
matrix[i][j] = value;
printf("%s%d\n","value stores in matrix: ",*matrix[i][j]);
}
}
}
matrix is a double array declared outside of any functions like so:
double matrix[1000][1000];
When I run the program, I get a separate value for the printout of 'value' and a different value for the printout of matrix[i][j] and I do not understand why they are different.
Thank you in advance!
Upvotes: 0
Views: 71
Reputation: 1420
printf("%s%d\n","value stores in matrix: ",*matrix[i][j]);
why do you deference the matrix??
change it to
printf("value stored in matrix: %lf ", matrix[i][j]);
you cannot specify the string literal like that in C. if you still want to print a string try
char *s = "value stores in matrix:"
then
printf("%s%lf\n",s,matrix[i][j]);
Upvotes: 0
Reputation: 628
You are dereferencing the result of matrix[i][j] which is wrong since the array notation by default dereferences the index. Remove the * before the matrix access. Also change your format specifier to %lf.
Upvotes: 0
Reputation: 15501
You shouldn't put the asterisk in front of matrix in printf, as that interprets the data as an address and "dereferences" it.
Also, if you want to print a double, you need to use %f instead of %d.
And if you want to calculate (i-j)/j
as a double (instead of integer division) you need to use a cast on one of the operands of the division operator.
for( i = 0; i < 1000;i++)
{
matrix[i][0] = i;
for( j = 1; j < 1000; j++)
{
double value = (i-j)/(double)j;
printf("value of i-j: %f\n", value);
matrix[i][j] = value;
printf("value stored in matrix: %f\n", matrix[i][j]);
}
}
Upvotes: 2