I have this piece of code:
// Returns the fibonacci range until the specified limit
int fibo(int** output, int limit)
{
// Must be 1 or more
if(limit < 1) return 0;
int* range = (int*)malloc(sizeof(int) * limit);
assert(range);
int i;
// Calculate the range
for(i = 0; i < limit; i++)
{
int value;
if(i == 0) va开发者_运维百科lue = 0;
if(i == 1) value = 1;
else value = range[i - 2] + range[i - 1];
range[i] = value;
}
*output = range;
return 1;
}
Running it with limit 15 outputs
65, 1, 66, 67, 133, 200, 333, 533, 866, 1399, 2265, 3664, 5929, 9593, 15522
which is not right at all. I suspect it's because I'm writing stuff like range[i - 2]
when that's not what I should be doing. I tried using the size of int as the hop between each value and got segmentation errors. Am I using []
correctly? Can anyone think of any other reason why my output is weird?
Here's all the code for the program
Change
if(i == 1) value = 1;
to
else if(i == 1) value = 1;
EDIT: Just realized this was already answered in the comments.
The issue is with your ifs You have two if statements
if(i == 0) value = 0;
and
if(i == 1) value = 1;
else value = range[i - 2] + range[i - 1];
If i is 0 then the second if evaluates to range[-2] + range[-1] so undefined data from memory
You need to be using else so that it is just one if statement (also as a point of style always use {} to make things clearer)
if(i == 0) {
value = 0;
} else if(i == 1) {
value = 1;
} else {
value = range[i - 2] + range[i - 1];
}
In this example probably even better to set range[0] and [1] before the loop and start the loop at 2 so no need for the if.
You're missing an else
between the if (i==0)
and if (i == 1)
, so the first time through both the 0 case and the 2+ case get run.
精彩评论