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

标签 c arrays memory-management dynamic malloc

我只是在玩 C 语言,我想要一个函数来生成斐波那契数列直到可变的最大项,并作为指向数组的指针返回。下面的代码工作得很好。

但我的问题实际上是它是否可以优化?我正在生成相同的斐波那契数列两次;首先找到有多少 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;
}

最佳答案

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
    }

关于c - 如何优化 malloc() 或动态填充未知大小的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20989662/

相关文章:

c++ - (C++) 当函数完成时分配在堆栈上的数组发生了什么?

c - 我们如何找到以下 C 程序的输出?

php - 将数组元素添加到从 sql 查询返回的行

php - 在不允许时添加到数组的正确异常类型?

c# - XML反序列化不在数组容器中的数组

c++ - 不断增加物理内存 Visual C++ CryptMsgClose 和 CryptReleaseContext

java - 我可以使用 C++ Boost shared_ptr 进行编程,就好像我在用 Java 编写代码一样,而不关心内存管理吗?

c - 为什么下面的代码会出现段错误问题?

c - 从文件中读取数组大小

c - 如何使用 libxml2 修改现有的 xml 文件?