Reputation: 13
I've just started learning C language. so I was doing some exercises and I had a problem with this one.
The code:
#include <stdio.h>
#include <math.h>
main()
{
double l[2];
double s, v, d;
int i;
for (i = 0; i < 3 && l[i] >= 0; i++)
{
scanf("%lf", &l[i]);
if ( l[i] < 0)
{
printf("Please type a positive value\n");
l[i+1]=-1;
}
}
if (l[0] >= 0 && l[1] >= 0 && l[2] >= 0)
{
s = 2 * ((l[0] * l[1]) + (l[0] * l[2]) + (l[1] * l[2]));
v = l[0] * l[1] * l[2];
d = sqrt(pow(l[0],2)+pow(l[1],2)+pow(l[2],2));
printf("%.2f\n%.2f\n%.2f\n", s, v, d);
}
}
The output gives right value for "s", but it changes l[2] value after "s" is stored, consequently it gives me wrong values for "v" and "d". I dont understand why l[2] is changing, anyone could help?
Upvotes: 0
Views: 102
Reputation: 90
Yeah, the answer for why the value is changing would be that since the memory location at l[2] is not allocated to your program, it is probably allocated to some other program, which is changing it's value. Even when you are reading some stuff into it, some other program is trying to change it again. Again, there is still a fair chance that the code would work fine if you are not running many processes. This is because, if the memory block containing l[2] is empty, it doesn't change over time. However, accessing variables out of your scope is a bad practice and would give you errors in other compilers.
Upvotes: 0
Reputation: 106012
Your program invokes undefined behavior;
1. You are reading/writing to an unallocated memory location.
2. In your for
loop you are reading uninitialized variable.
Upvotes: 1
Reputation: 124642
Accessing l[2]
results in undefined behavior. Arrays in C are 0-indexed and l
only contains two elements, i.e., l[0]
and l[1]
. Your loop should be:
for (i = 0; i < 2 && l[i] >= 0; i++)
And you should probably just store the size in a constant.
Upvotes: 2
Reputation: 108978
The definition
double l[2];
defines an array with space for 2 values of type double
.
The array elements can be accessed with l[0]
and l[1]
. Accessing l[2]
(as you are doing) is an error.
Upvotes: 2