如何优化malloc()或动态填充未知大小的内存?

时间:2014-01-08 07:40:34

标签: c arrays memory-management dynamic malloc

我只是在C中玩,我想要一个能够生成Fibonacci序列的函数,该函数最多可变一个变量,并作为指向数组的指针返回。下面的代码工作得很好。

但我的问题实际上是否可以进行优化?我正在生成相同的斐波那契序列两次;首先找到 fibterms 有多少 maxterm 并分配足够的内存以适应所有条款,并第二次用我所说的术语填充该内存现在发现了两次。

我是否忽略了一些更关键的malloc()或有没有办法将这两个循环结合起来?我可以不断调用malloc并将旧的fib复制到新的吗?重复呼唤新记忆是不是很糟糕?

int* genFib(int maxterm) 
{   
    // generate a way for x to be the fibonacci term
    // with y being the previous term
    int x = 1, y = 1;

    // fibterms is a global variable that counts the
    // number of terms, to create the right size array.
    // it needed to be global to find the size elsewhere
    do
    {
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
    }
    while (x < maxterm);

    // the array has enough space allocated now, but
    // is empty for the moment.
    int* fib = malloc(sizeof(int) * fibterms);   

    // i need to now redo my previous loop just to
    // fill the array with the correct terms, so all
    // counters and terms are reset.
    x = 1, y = 1;
    fibterms = 0;

    // same loop as above, but 
    // filling the array this time
    do
    {
        fib[fibterms] = x;
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
    }
    while (x < maxterm);
    return fib;
}

1 个答案:

答案 0 :(得分:1)

int* fib = malloc(sizeof(int));   
    x = 1, y = 1;
    fibterms = 0;

    // same loop as above, but 
    // filling the array this time
    do
    {
        fib[fibterms] = x;
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
        fib = (int *)realloc(fib , sizeof(int)*(fibterms+1));//fibterms is a int from 0
    }