简体   繁体   中英

How to I operate on int arrays declared using malloc?

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)  value = 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.

您错过了if (i==0)if (i == 1)之间的else ,因此第一次通过0情况和2+情况进行运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM